gpt4 book ai didi

rust - 如何在没有 'cannot move out of borrowed content' 错误的情况下返回值?

转载 作者:行者123 更新时间:2023-11-29 08:06:23 26 4
gpt4 key购买 nike

<分区>

我是 Rust 的新手,正在研究它。这是我的第一个程序,似乎我已经遇到了可怕的借用检查器。 :)

pub struct Foo<T> {
memory: Vec<T>
}

impl<T> Foo<T> { {
pub fn set(&mut self, value: T) {
self.memory.push(value);
}

pub fn get(&self, index: usize) -> Option<&T> {
Some(&self.memory[index])
}
}

它编译得很好,但我想返回值而不是 get 函数的引用。

如果我这样做

pub fn get(&self, index: usize) -> Option<T> {
Some(*&self.memory[index])
}

失败:

错误:无法移出借用的内容 [E0507]
一些(*&self.memory[index])

我只是不知道借用检查器为什么会这样。

如何返回值?谁能赐教一下?

Rem: 这不是重复的问题。我不要求别人解释“索引内容”是什么意思,而是如何在没有 cannot move out of borrowed content 错误的情况下返回值。

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