参数/模式中“& variable"的含义 [英] Meaning of '&variable' in arguments/patterns
问题描述
&variable
在模式或闭包参数中使用时是什么意思?
for &code in self.exit_code.iter() { ... }
let mut new_seps = do seps.iter().fold(~[]) |result, &next| { ... }
在这里,在for
循环和闭包定义中有&code
和&next
. &
表示这些含义是什么?为什么我们不能简单地使用code
和next
而没有&"号呢?它与模式匹配中的ref
限定符有关吗?它与特征实现中self
参数中的&
有关吗?
在当前Rust参考手册或教程中.目前,我认为这是某种隐式取消引用(如果我在模式中省略了&
,则会出现错误消息,这是隐式取消引用的原因),但是我不确定.
这是一个模式匹配,解构"了类型为&T
的东西.也就是说,在
let &x = &1i;
x
的类型为int
,值1.因此,它实际上与ref
相反(@KerrekSB所说的话,ref x
是通过引用而不是通过值捕获的.)
可以认为它类似于
match returns_an_option() {
Some(a) => { ... }
None => { ... }
}
&T
的构造函数是&
,而不是Some
或None
.
在这种特定情况下,我想seps
是一个向量(您所指出的错误表明它可能是&[&str]
),所以.iter()
返回一个实现Iterator<& &str>
的对象,即,它是一个对向量(&str
)元素的引用进行迭代的迭代器,因此,您需要以某种方式取消引用next
才能到达原始的&str
.可以通过&
进行模式匹配(如代码所示)来实现(如代码所示),或者 与*next
一起使用.
(请注意,&
模式仅适用于隐式可复制类型,因为不能将所有权从引用/借用指针(即&T
)移出.)
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| { ... }
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?
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.
It's a pattern match, "destructuring" something of type &T
. That is, in
let &x = &1i;
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).
One can regard it as similar to
match returns_an_option() {
Some(a) => { ... }
None => { ... }
}
except the constructor of &T
is &
, not Some
or None
.
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.
(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屋!