gpt4 book ai didi

rust - 如何正确使用 Rust 中的 IndexMut 特性?

转载 作者:行者123 更新时间:2023-11-29 08:04:21 27 4
gpt4 key购买 nike

我最近玩弄了 rust,并尝试为 Point 结构实现索引,这样 some_point[2] 就会给我 z 坐标。

但是我无法编译下面的代码。我错过了什么?

struct Point {
x: int,
y: int,
z: int
}

impl IndexMut<uint, int> for Point {
fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut int {
& mut match *index {
0 => self.x,
1 => self.y,
2 => self.z,
_ => 0 //TODO: add proper error handling
}
}
}

这是我得到的错误:

[me@localhost rust]$ rustc blabla.rs && ./blabla
blabla.rs:25:11: 30:6 error: borrowed value does not live long enough
blabla.rs:25 & mut match *index {
blabla.rs:26 0 => self.x,
blabla.rs:27 1 => self.y,
blabla.rs:28 2 => self.z,
blabla.rs:29 _ => 0
blabla.rs:30 }
blabla.rs:24:63: 31:4 note: reference must be valid for the lifetime 'a as defined on the block at 24:62...
blabla.rs:24 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut int {
blabla.rs:25 & mut match *index {
blabla.rs:26 0 => self.x,
blabla.rs:27 1 => self.y,
blabla.rs:28 2 => self.z,
blabla.rs:29 _ => 0
...
blabla.rs:24:63: 31:4 note: ...but borrowed value is only valid for the block at 24:62
blabla.rs:24 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut int {
blabla.rs:25 & mut match *index {
blabla.rs:26 0 => self.x,
blabla.rs:27 1 => self.y,
blabla.rs:28 2 => self.z,
blabla.rs:29 _ => 0
...
error: aborting due to previous error

很抱歉,stackoverflow 强制我将错误消息格式化为代码。我希望它仍然具有足够的可读性。

最佳答案

您的匹配 block 复制 self.x 等,然后该函数尝试返回对它的可变引用(至少这是我的解释)。试试这个吧

match *index {
0 => & mut self.x,
1 => & mut self.y,
2 => & mut self.z,
_ => fail!("")
}

关于rust - 如何正确使用 Rust 中的 IndexMut 特性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25399245/

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