小编wan*_*021的帖子

为什么元组或结构的大小不是成员的总和?

assert_eq!(12, mem::size_of::<(i32, f64)>()); // failed
assert_eq!(16, mem::size_of::<(i32, f64)>()); // succeed
assert_eq!(16, mem::size_of::<(i32, f64, i32)>()); // succeed
Run Code Online (Sandbox Code Playgroud)

为什么不是 12 (4 + 8)?Rust 对元组有特殊处理吗?

memory-layout rust

11
推荐指数
2
解决办法
360
查看次数

为什么用`#[cfg(test)]`注释的无效代码仍然会导致构建失败?

cargo build以下代码运行将成功:

#[cfg(test)]
mod tests {
    #[test]
    fn func() { 
        let x = 1;
        sss
    }
}
Run Code Online (Sandbox Code Playgroud)

但此代码会失败:

#[cfg(test)]
mod tests {
    #[test]
    fn func() {
        sss
        let x = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)
#[cfg(test)]
mod tests {
    #[test]
    fn func() { 
        let x = 1;
        sss
    }
}
Run Code Online (Sandbox Code Playgroud)

《Rust Book》中关于测试组织的一节说:

测试模块上的注释#[cfg(test)]告诉 Rust 仅在运行时编译并运行测试代码cargo test,而不是在运行时编译 和运行测试代码cargo build。

那么为什么 Rust 仍然可以编译mod tests带有 注释的代码#[cfg(test)]呢?

conditional-compilation rust

6
推荐指数
1
解决办法
297
查看次数

Rust 中的闭包捕获

我刚刚发现下面的代码

fn create_fn_once() -> impl FnOnce(char) -> String {
    let text = "text".to_string();  // not implement the `Copy` trait
    let y = 1;                      // implement the `Copy` trait

    |x| {
        move_x(text);   // ok
        move_x(y);      // error: `y` is borrowed here
        x.to_string()
    }
}

fn move_x<T: Sized>(x: T) {}
Run Code Online (Sandbox Code Playgroud)

失败(游乐场)

error[E0373]: closure may outlive the current function, but it borrows `y`, which is owned by the current function
 --> src/lib.rs:5:5
  |
5 |     |x| {
  |     ^^^ may outlive …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
174
查看次数

Pin::as_mut(&amp;mut self)

Pin::as_mut来自- pin.rs的来源:

impl<P: DerefMut> Pin<P> {
    ...
    pub fn as_mut(&mut self) -> Pin<&mut P::Target> {    
        unsafe { Pin::new_unchecked(&mut *self.pointer) }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么&mut *self.pointer用 代替self.pointer,下面这句话有什么问题吗?

unsafe { Pin::new_unchecked(self.pointer) }
Run Code Online (Sandbox Code Playgroud)

rust

1
推荐指数
1
解决办法
829
查看次数

结构体可变引用的借用错误

struct C {
    p: String,
    q: String,
}

impl C {
    fn call(&mut self) {}
}

fn main(){
    let mut c = C { p: "p".to_string(), q: "q".to_string() };        
    let p = &mut c.p; // first mutable borrow occurs here
    let q = &mut c.q; // second mutable borrow doesn't occur here, why???
    c.call();         // second mutable borrow occurs here  // error[E0499]: cannot borrow `c` as mutable more than once at a time
    p.push('x');
    q.push('y');
}
Run Code Online (Sandbox Code Playgroud)

let q = &mut …

rust borrow-checker mutable-reference

1
推荐指数
1
解决办法
74
查看次数