我是Rust世界的新手。
作为练习,这是我试图解决的问题:
fn main() {
let s = give_ownership();
println!("{}", s);
}
// Only modify the code below!
fn give_ownership() -> String {
let s = String::from("hello, world");
// Convert String to Vec
let _s = s.into_bytes();
s
}
我已经打通了。
然而,当我不加修改地编译上面的练习代码片段时,我不太明白编译器在这里告诉我什么,正如下面的注释:Compiling playground v0.0.1 (/playground)
error[E0382]: use of moved value: `s`
--> src/main.rs:12:5
|
9 | let s = String::from("hello, world");
| - move occurs because `s` has type `String`, which does not implement the `Copy` trait
10 | // Convert String to Vec
11 | let _s = s.into_bytes();
| ------------ `s` moved due to this method call
12 | s
| ^ value used here after move
|
note: this function takes ownership of the receiver `self`, which moves `s`
我猜这个注释是关于函数into_bytes()的。关于这个函数,RustDoc是这样说的:
使用String对象,因此不需要复制其内容。
有人能详细说明一下吗?
into_bytes()
接受self
(即拥有的自我,而不是引用)。
这意味着它获得了调用它的字符串的所有权。在概念上和下面是一样的:
fn main() {
let s = String::from("hello");
take_string(s);
println!("{s}"); // ERROR
}
fn take_string(s: String) {}
这很有用,因为它允许您在重用分配的同时将String
转换为Vec<u8>
。String
实际上只是Vec<u8>
,保证字节是有效的UTF-8。
所以一旦你写了let _s = s.into_bytes()
,s
中的数据现在已经移动到_s
,所以你不能从你的函数返回s
。这里没有
如果你只想返回字符串,你可以只返回String::from("stuff")