这是我在Rust文档中看到的两个函数签名:
fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }
fn modify_foo(foo: &mut i32) { *foo += 1; *foo }
Run Code Online (Sandbox Code Playgroud)
为什么不同的位置mut?
似乎第一个函数也可以声明为
fn modify_foo(foo: mut Box<i32>) { /* ... */ }
Run Code Online (Sandbox Code Playgroud) 我想在堆栈上创建一个可变结构,并从辅助函数中改变它.
#[derive(Debug)]
struct Game {
score: u32,
}
fn addPoint(game: &mut Game) {
game.score += 1;
}
fn main() {
let mut game = Game { score: 0 };
println!("Initial game: {:?}", game);
// This works:
game.score += 1;
// This gives a compile error:
addPoint(&game);
println!("Final game: {:?}", game);
}
Run Code Online (Sandbox Code Playgroud)
试图编译这个给出:
error[E0308]: mismatched types
--> src/main.rs:19:14
|
19 | addPoint(&game);
| ^^^^^ types differ in mutability
|
= note: expected type `&mut Game`
found type `&Game`
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我正在编写一个安全的Rust层,我可以从Rust中的C库中调用函数.我使用rust-bindgen生成了不安全的绑定,但是我对Rust和C在传递指针方面的工作方式之间的差异感到有些困惑.
C函数看起来像这样:
bool imeGet(unsigned char address, int *value);
Run Code Online (Sandbox Code Playgroud)
它读取I2C传感器address,存储结果value,并TRUE在成功时返回.
Bindgen的Rust功能如下所示:
pub fn imeGet(address: ::std::os::raw::c_uchar,
value: *mut ::std::os::raw::c_int) -> bool;
Run Code Online (Sandbox Code Playgroud)
我的安全来电者目前看起来像这样:
pub fn ime_get(addr: u8) -> i32 {
let v: &mut i32 = 0;
unsafe {
imeGet(addr, v);
*v
}
}
Run Code Online (Sandbox Code Playgroud)
由于这个代码不能编译= 0.当我没有那个时,编译器抱怨v可能没有被初始化.我的目的是在这个函数中处理成功,并返回i32值.
我如何处理*mut c_int参数的行为?我试图声明v为引用并返回其解除引用的值(上图),但这不起作用.我也尝试过返回v,但我真的不希望返回值保持可变.
我对Rust很陌生,但我在C中确实有一个不错的背景,这可能是我混乱的根源.