0

The only difference between these two examples is that the first has an & in &[1, 2, 4]. Both examples work. I tried to find documentation for this reason but haven't found any yet. What is the reason here? Links to documentation would be appreciated.

Example 1:

fn main() {
    let x = &[1, 2, 4];
    let mut iterator = x.iter();
    assert_eq!(iterator.next(), Some(&1));
    assert_eq!(iterator.next(), Some(&2));
    assert_eq!(iterator.next(), Some(&4));
    assert_eq!(iterator.next(), None);
    println!("Ok.");
}

Example 2:

fn main() {
    let x = [1, 2, 4];
    let mut iterator = x.iter();
    assert_eq!(iterator.next(), Some(&1));
    assert_eq!(iterator.next(), Some(&2));
    assert_eq!(iterator.next(), Some(&4));
    assert_eq!(iterator.next(), None);
    println!("Ok.");
}
Shepmaster
  • 274,917
  • 47
  • 731
  • 969
mitnk
  • 2,569
  • 2
  • 18
  • 27
  • Rust automatically dereferences the subject of a method. Your code also works for `&&&&&&&&&&[1, 2, 4];` – Shepmaster Jan 03 '18 at 02:50
  • I saw this in doc, this is removing `&` when needed. It doesn't say rust can add `&` as needed - i.e. `iter(&self)` could call with `x.iter()`. (It is explained in the SO answer you linked above). – mitnk Jan 03 '18 at 03:18
  • It's explained in the book. The first reference I could find on my phone is in the [method syntax chapter](https://doc.rust-lang.org/book/second-edition/ch05-03-method-syntax.html#wheres-the---operator) – Shepmaster Jan 03 '18 at 03:23
  • Thanks this section is what I missed. It states "rust has a feature called automatic **referencing** and dereferencing". It seems most places only mentioned [auto deref](https://doc.rust-lang.org/book/first-edition/deref-coercions.html). This is the first place I saw "auto ref". – mitnk Jan 03 '18 at 03:55

0 Answers0