Rust 中星号符号的用法是什么? [英] What is the usage of the asterisk symbol in Rust?
问题描述
我是 Rust 的新手,我不理解以下代码:
I'm new to Rust and I don't understand the following piece of code:
let mut x = 5;
{
let y = &mut x;
*y += 1;
}
println!("{}", x);
来自 Rust 站点的解释:
您还会注意到我们在 y
前面添加了一个星号 (*
),使其成为 *y
,这是因为 y
是 &mut
引用.您还需要使用星号 [sic] 来访问参考文献的内容.
You'll also notice we added an asterisk (
*
) in front ofy
, making it*y
, this is becausey
is a&mut
reference. You'll need to use astrisks [sic] to access the contents of a reference as well.
如果*y
是一个引用,为什么下面的代码有效
If *y
is a reference, why does the following code work
fn main() {
let mut x = 5;
{
let y = &mut x;
println!("{}", y);
}
}
我知道我没有修改这里的值,但有什么区别以及为什么y += 1;
会不起作用吗?
I know I'm not modifying the value here, but what is the difference and why
would y += 1;
not work?
推荐答案
如果
*y
是引用
*y
是不是参考.y
是一个参考;*y
dereferences y
,允许您访问被引用的值.
*y
is not a reference. y
is a reference; *y
dereferences y
, allowing you access to the referred-to value.
[+=
和 println!
之间有什么区别]
what is the difference [between
+=
andprintln!
]
println!
是一个自动引用的宏给它的参数.此外,Display
trait(通过格式字符串中的 {}
使用)是为所有对自身实现 Display
的类型的引用实现的(impl<'a, T> Display for &'a T where T: Display + ?Sized
).
println!
is a macro that automatically references the arguments given to it. In addition, the Display
trait (used via {}
in the format string) is implemented for all references to types that themselves implement Display
(impl<'a, T> Display for &'a T where T: Display + ?Sized
).
因此,println!("{}", y);
实际上是打印出对值引用的引用.由于 Display
的实现,这些中间引用会自动取消引用.
Thus, println!("{}", y);
is actually printing out a reference to a reference to a value. Those intermediate references are automatically dereferenced due to the implementation of Display
.
+=
是通过 AddAssign
特性.标准库仅实现向自身添加整数类型(impl AddAssign
).这意味着您必须添加适当级别的取消引用才能使两边都为整数.
+=
, on the other hand, is implemented via the AddAssign
trait. The standard library only implements adding an integer type to itself (impl AddAssign<i32> for i32
). That means that you have to add an appropriate level of dereferencing in order to get both sides to an integer.
这篇关于Rust 中星号符号的用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!