gpt4 book ai didi

vector - 如何编写一个将元素添加到向量的函数,允许在插入之前更改元素?

转载 作者:行者123 更新时间:2023-11-29 08:07:48 24 4
gpt4 key购买 nike

我正在尝试制作一个涉及结构向量的简单示例来学习 Rust。我发现的 Rust 文献中的所有向量示例都只使用整数向量。

我想写一个函数来填充一个向量,允许改变插入元素的可能性,我不知道该怎么做。我总是遇到编译器 error[E0308]: mismatched typespush 方法,因为 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 的引用存储在声明为包含整个 PointVec 中。由于 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);
}

请注意,originp1 都不需要是可变的,因为该函数在拥有它时不会修改任何一个。它将所有权转移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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com