Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

pointers - Meaning of '&variable' in arguments/patterns

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...