The following C# code compiles fine:
static readonly List<int> list = new List<int>();
static void Main(string[] args)
{
list.Add(1);
list.Add(2);
list.Add(3);
}
If I write similar code in Rust, it won't compile because it cannot borrow immutable v
as mutable:
let v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
How does the push
function know v
is immutable?
All variables are immutable by default. You must explicitly tell the compiler which variables are mutable though the mut
keyword:
let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
Vec::push
is defined to require a mutable reference to the vector (&mut self
):
fn push(&mut self, value: T)
This uses method syntax, but is conceptually the same as:
fn push(&mut Vec<T>, value: T)
I highly recommend that you read The Rust Programming Language, second edition. It covers this beginner question as well as many other beginner questions you will have.