我正在尝试制作一个涉及结构向量的简单示例来学习 Rust。我发现 Rust 文献中的所有向量示例都只使用整数向量。
我想编写一个旨在填充向量的函数,允许更改插入元素的可能性,我不知道该怎么做。我总是遇到编译器错误[E0308]:类型不匹配
push
方法,因为 elem
是对 Point
的引用。所以
push()
需要一个Point
结构,因为v
是Point
的向量- 但是如果我想修改
elem
,我需要传递一个(可变?)引用
什么是正确的做法?
// structure used everywhere in Rust examples
#[derive(Debug)]
struct Point {
x: i16,
y: i16
}
fn add_element(v: &mut Vec<Point>, elem: &Point) {
// modify element
elem.x = 0;
// add element
v.push(elem);
}
// this example is meant to study a vector of structs
fn main() {
// declare 2 points. By default, live on the stack
let origin = Point {x:0, y:0};
println!("origin address\t: {:p}", &origin);
let mut p1 = Point {x:1, y:1};
println!("p1 address\t: {:p}", &p1);
// declare a new vector of structs. Allocation is made in the heap
// declare mutable because we'll add elements to vector
let mut v: Vec<Point> = Vec::new();
// add points
add_element(&mut v, &origin);
add_element(&mut v, &p1);
// change p1
p1.x = 2;
p1.y = 2;
}
最佳答案
我们一起来看看错误信息:
error[E0308]: mismatched types
--> src/main.rs:10:12
|
10 | v.push(elem);
| ^^^^ expected struct `Point`, found &Point
|
= note: expected type `Point`
= note: found type `&Point`
该代码尝试在声明为保存整个Point
的Vec
中存储对Point
的引用。由于 Rust 是一种静态强类型语言,编译器会告诉您不能这样做。修复方法是按值接受 Point
:
fn add_element(v: &mut Vec<Point>, elem: Point)
这会导致下一个错误:
error: cannot assign to immutable field `elem.x`
--> src/main.rs:9:5
|
9 | elem.x = 0;
| ^^^^^^^^^^
您无法更改 elem
的成员,因为它未标记为可变。值的可变性是绑定(bind)的一个属性,所以让我们这样做:
fn add_element(v: &mut Vec<Point>, mut elem: Point)
然后更改该函数的调用以适应:
fn main() {
let origin = Point { x: 0, y: 0 };
let p1 = Point { x: 1, y: 1 };
let mut v = Vec::new();
add_element(&mut v, origin);
add_element(&mut v, p1);
}
请注意,origin
和 p1
都不需要是可变的,因为该函数在拥有它时不会修改它们。它将所有权转移给add_element
,后者选择使其可变。
but if I want to modify
elem
, I need to pass a (mutable?) reference
正如您所看到的,在将整个值传输到函数时,您可以简单地使 elem
参数可变。由于函数拥有该值,因此它可以完全控制它,包括选择使其可变。
关于vector - 如何编写一个函数,将元素添加到向量中,并允许在插入之前更改元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42565964/