gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:12:40 25 4
gpt4 key购买 nike

如果我有以下方法:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com