0

Essentially, I wanted to know the exact difference between

* Vec<usize>
* Vec<&usize>
* Vec<&mut usize>
* Vec<&mut &usize>

Specifically the last one

1
  • The distinction has nothing to do with Vec. Commented Feb 11, 2023 at 23:57

1 Answer 1

4
  • Vec<usize> - a vector containing usize numbers
  • Vec<&usize> - a vector containing references to usize numbers that are stored somewhere else
  • Vec<&mut usize> - same as Vec<&usize>, but the referenced usize numbers can be modified
  • Vec<&mut &usize> - a vector containing references that point to other references that point to usize. The referenced references can be modified, but the usize numbers can not.

Additional remarks:

  • Vec<&usize> is pointless. A &usize can only be used to access the values read-only, and everything that it can do can be done more efficiently with a Vec<usize>. For primitive types like usize, passing by-value is usually faster than by-reference for non-mutable access.
  • Vec<&mut &usize> is very exotic and probably won't ever be encountered in real code.
Sign up to request clarification or add additional context in comments.

2 Comments

I guess for completeness' sake, we can also throw in Vec<&mut &mut usize>. A vector containing references that point to other references that point to usize. The referenced references can be modified, as can the usize numbers.
@cadolphs There are infinitely more if you want completeness. However, for real projects, Vec<usize> and Vec<&mut usize> are probably the only two that matter. Although even that might be a stretch; realistically you will encounter Vec<usize>, &mut Vec<usize> and &[usize]. Maybe in rare cases &mut [usize].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.