gpt4 book ai didi

rust - 如何在 Rust 中进行就地赋值?

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

在 C++ 中,我可以在将变量 var 打印到屏幕上时进行就地赋值:

int var = 5;
std::cout << ( var += 1 ) << std::endl;

我这样做是因为 Rust 没有自减运算符 ++ & --。我在 Rust 中尝试过:

let mut counter = 0;
println!("{}", (counter += 1));

它在说:

error[E0277]: the trait bound `(): std::fmt::Display` is not satisfied
--> src/main.rs:3:20
|
3 | println!("{}", (counter += 1));
| ^^^^^^^^^^^^^^ the trait `std::fmt::Display` is not implemented for `()`
|
= note: `()` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
= note: required by `std::fmt::Display::fmt`

最佳答案

最短的解决方案是返回值:

let mut counter = 0;
println!("{}", {counter += 1; counter});

但老实说,我会说这不是惯用的 Rust,你不妨把它写在另一行上:

let mut counter = 0;
counter += 1;
println!("{}", counter);

较长的答案是您无法获取赋值的值。 AddAssign 的特征定义为

pub trait AddAssign<Rhs = Self> {
fn add_assign(&mut self, Rhs);
}

值得注意的是,该方法没有返回任何值。 Rust 对于赋值的结果没有有用的值,因为通常没有。所有权语义使得弄清楚像 let x = String::new(); 这样的东西的“返回值”应该是什么变得复杂。如果它是一个 String,那么 x 持有的所有权会发生什么变化?

由于所有表达式都返回一些类型,因此赋值返回空元组 (()),也称为单元类型。 p>

这种情况下,值是一个整数,它实现了Copy特征。这意味着您可以轻松地从 block 中返回一个副本。

相同的解决方案对 String 也“有效”,直到您之后尝试使用它:

let mut string = String::new();
println!("{}", {string += "a"; string});
println!("{}", string); // use of moved value: `string`

可以通过返回引用来修复:

println!("{}", {string += "a"; &string});

但在这一点上,实际上没有任何“节省”要做。

关于rust - 如何在 Rust 中进行就地赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058762/

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