以下 C# 代码可以正常编译:
static readonly List<int> list = new List<int>();
static void Main(string[] args)
{
list.Add(1);
list.Add(2);
list.Add(3);
}
如果我用 Rust 编写类似的代码,它不会编译,因为它不能将不可变的 v
借用为可变的:
let v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
push
函数如何知道 v
是不可变的?
最佳答案
所有变量默认都是不可变的。你必须 explicitly tell the compiler which variables are mutable通过 mut
关键字:
let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
Vec::push
被定义为需要对向量的可变引用 (&mut self
):
fn push(&mut self, value: T)
这使用 method syntax ,但在概念上与:
fn push(&mut Vec<T>, value: T)
我强烈推荐您阅读The Rust Programming Language, second edition .它涵盖了这个初学者问题以及您将遇到的许多其他初学者问题。
关于rust - Rust 如何知道变量是否可变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46266400/