Avatar ·

Rust中的“cannot move out of borrowed content”错误:原因与修复

你好!我开始学习Rust,遇到了一个无法理解的错误。代码: ```rust fn main() { let s = String::from("hello"); let r = &s; let s2 = *r; // 错误:cannot move out of borrowed content println!("{}", s2); } ``` 我以为`*r`解引用会给我字符串`s`的所有权。但编译器说:“cannot move out of `*r` which is behind a shared reference”。为什么?我只是想复制值。 同样的情况也发生在向量上: ```rust fn get_first(v: &Vec) -> i32 { v[0] // 错误:cannot move out of borrowed content } ``` 我理解Rust严格管理所有权,但我不明白为什么不能简单地通过引用“取走”值。在其他语言(C++、Python)中这是可行的。如何正确地从引用中获取值?为什么存在这个限制? 请解释如何修复这些示例以及错误的深层原因。提前感谢! <<>>

简要:为什么