Meaning of ‘&variable’ in arguments/patterns

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

Leave a Comment