作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我有以下方法:
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/
我是一名优秀的程序员,十分优秀!