rust - 如何将 Box 值传递给函数

标签 rust

如果我有以下方法:

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/

相关文章:

rust - 为什么我不必为类型实现 Any 特性,即使它是必需的?

rust - 尝试拆分字符串时,未为 `FnMut<(char,)>` 实现特征 `String`

amazon-web-services - 如何将我的结构放入Rust中用于AWS Kinesis的PutRecordInput中?

rust - 返回对外部引用的过滤向量的引用时如何安抚借用检查器

asynchronous - 如何限制 async_trait 函数的返回值来实现同步?

rust - 尝试在宏扩展中实现特征时出现宏错误

rust - 为什么我要在特征上而不是作为特征的一部分来实现方法?

string - 为什么我不能像在 trim_right_matches() 中那样在 trim_matches() 中使用 &str?

python-3.x - 在 pyenv 中将 matplotrust 与 python3 解释器一起使用

rust - 是否可以在 &mut 周围创建一个包装器,其作用类似于 &mut