参数/模式中“&variable"的含义 [英] Meaning of '&variable' in arguments/patterns
问题描述
&variable
在模式或闭包参数中使用时是什么意思?
What does &variable
mean when it is used in patterns or closure arguments?
for &code in self.exit_code.iter() { ... }
let mut new_seps = do seps.iter().fold(~[]) |result, &next| { ... }
这里我们有 &code
和 &next
在 for
循环和闭包定义中.&
登录这些是什么意思?为什么我们不能简单地使用 code
和 next
而没有 & 符号?它与模式匹配中的 ref
限定符有关吗?它是否与 trait 实现中 self
参数中的 &
相关?
Here we have &code
and &next
in for
loop and closure definition. What do &
sign in these mean? Why cannot we simply use code
and next
, without the ampersand? Is it related to ref
qualifier in pattern matching? Is it related to &
in self
argument in trait implementations?
我在 current 中都找不到有关此语法的任何内容Rust 参考手册 和教程.目前,我认为这是某种隐式取消引用(这是从错误消息中得出的,如果我在模式中省略 &
,则会出现该错误消息),但我不确定.
I couldn't find anything on this syntax neither in current Rust reference manual nor in tutorial. Currently I think this is some kind of implicit dereferencing (this follows from error message which appears if I omit &
in the pattern), but I'm not sure.
推荐答案
这是一个模式匹配,解构"&T
类型的东西.也就是说,在
It's a pattern match, "destructuring" something of type &T
. That is, in
let &x = &1i;
x
的类型为 int
,值为 1.所以它实际上与 ref
相反(它做了@KerrekSB 所说的,ref x
通过引用而不是通过值捕获).
x
has type int
, and value 1. So it's actually the opposite to ref
(which does what @KerrekSB is saying, ref x
captures by reference rather than by value).
可以认为它类似于
match returns_an_option() {
Some(a) => { ... }
None => { ... }
}
除了&T
的构造函数是&
,不是Some
或None
.
except the constructor of &T
is &
, not Some
or None
.
在这个特定的例子中,我猜 seps
是一个向量(你陈述的错误表明它可能是一个 &[&str]
),所以 .iter()
返回一个实现 Iterator<& 的对象&str>
,也就是说,它是对向量元素(&str
)的引用的迭代器,因此,您需要取消引用next
以某种方式获得原始 &str
.这可以通过 &
在模式匹配中完成(如代码所示)或与 *next
一起使用.
In this specific instance, I guess seps
is a vector (the error you state indicates it's probably a &[&str]
), so the .iter()
returns an object that implements Iterator<& &str>
, that is, it is an iterator over references to the elements of the vector (&str
), thus, you need to dereference next
somehow to get to the original &str
. This can be done by &
in a pattern match (as the code demonstrates) or with *next
when it is used.
(请注意,&
模式仅适用于隐式可复制类型,因为不能从引用/借用 指针(即 &T
).)
(Note that the &
patterns only work with implicitly copyable types, as one cannot move ownership out from a reference/borrowed pointer (i.e. &T
).)
这篇关于参数/模式中“&variable"的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!