gpt4 book ai didi

rust - 借用 Rust 中的检查器和函数参数,正确还是过度热心?

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

<分区>

当可变参数作为函数参数传递时,借用检查器不允许将其用于构造其他参数,即使这些参数在没有引用的情况下克隆值也是如此。

虽然在函数外部分配变量始终是一个选项1,但从逻辑上讲,这似乎过于热心,借用检查器可能会考虑到这一点。

这是按预期工作还是应该解决的问题?

#[derive(Debug)]
struct SomeTest {
pub some_value: f64,
pub some_other: i64,
}

fn some_fn(var: &mut SomeTest, other: i64) {
println!("{:?}, {}", var, other);
}

fn main() {
let mut v = SomeTest { some_value: 1.0, some_other: 2 };
some_fn(&mut v, v.some_other + 1);

// However this works!
/*
{
let x = v.some_other + 1;
some_fn(&mut v, x);
}
*/
}

给出这个错误:

  --> src/main.rs:14:21
|
14 | some_fn(&mut v, v.some_other + 1);
| - ^^^^^^^^^^^^ use of borrowed `v`
| |
| borrow of `v` occurs here

参见:playpen .


[1]:尽管一次性赋值有时确实提高了可读性,但强制将它们用于参数会鼓励使用作用域,以避免一次性使用变量污染 namespace ,导致函数调用,否则将是一行 -被括在大括号中并定义变量...我想尽可能避免这种情况,尤其是当借用检查器可以支持的要求时。

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