1

The question arises from following code:

#[derive(Debug)]
struct Foo {
  x: i32,
}

pub fn main() {
  let a = vec![Foo{x:1}, Foo{x:2}];
  println!("{:?}", a[1]);
  println!("{:?}", &a[1]);
  println!("{:?}", *(&a[1]));
}

After cargo run, the code outputs:

Foo { x: 2 }
Foo { x: 2 }
Foo { x: 2 }

Which caused me wondering:

  1. Why println!("{:?}", a[1]) won't take ownership of 2nd element?
  2. What are differences between passing by reference and by value under this circumstance?
  3. Is it possible to implement similar functions capable of accepting parameters by value(without taking ownership) and by reference, without resorting to macro system?
ji chengde
  • 81
  • 4
  • To clarify the last point: no, you can't write a regular function that takes its parameters by implicit reference; that's only possible with the `format!`/`println!` family because they are macros. – trent Nov 02 '19 at 22:57

0 Answers0