如果我有以下方法:
fn borrow_func(c: Box<i32>) {
// some code
}
fn main(){
let a = Box::new(5i32);
let b = a;
borrow_func(b);
println!("b contains: {}", b);
}
因为堆中的资源会在borrow_func中被释放,请问有什么办法可以避免吗?
如果我尝试像下面那样在 borrow_func 中使用借用,我会得到一个
编译错误:
expected
Box<i32>
,
found&_
fn borrow_func(&c: Box<i32>) {
}
编译器好像没有b的指针类型?
我怎样才能使这个工作?
最佳答案
您的 borrow_func
实际上取得了装箱变量的所有权。您应该更改 borrow_func
的签名以反射(reflect)借用,如下所示:
fn borrow_func(c: &i32) {
// some code
}
fn borrow_func2(c: &Box<i32>) {
// some code
}
fn main(){
let a = Box::new(5i32);
let b = a;
borrow_func(&b);
borrow_func2(&b);
println!("b contains: {}", b);
}
您也可以使用 &Box 的简单引用。有关借阅的更多信息,请查看:https://doc.rust-lang.org/book/references-and-borrowing.html
Vladimir添加了一个有用的信息:
pointers to boxes like &Box are unidiomatic and completely pointless - they introduce unnecessary double indirection and give nothing useful back. Just plain reference (&i32) is always the way to go.
关于rust - 如何将 Box 值传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34707994/