我正在做一些使用 Rust 线程的练习。我想打印分块字符串,但我无法解决我偶然发现的生命周期问题。这是我的代码:
let input = "some sample string".to_string();
let mut threads = vec![];
for chunk in input.chars().collect::<Vec<char>>().chunks(2) {
threads.push(thread::spawn({
move || -> () {
println!("{:?}", chunk);
}
}))
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行它时,出现以下错误:
error[E0716]: temporary value dropped while borrowed
--> src\main.rs:7:18
|
7 | for chunk in input.chars().collect::<Vec<char>>().chunks(2) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^----------
| | |
| | temporary value is freed at the end of this statement
| creates a temporary which is freed while still in use
| argument requires that borrow lasts for `'static`
Run Code Online (Sandbox Code Playgroud)
我知道编译器不知道线程内的块是否不会比input变量寿命更长。但我能做些什么来修复这个代码呢?我尝试过clone()向量,但没有帮助。
块的类型为&[char],与字符串具有相同的生命周期。
在这里简单地克隆是行不通的,因为在编译时它不知道 char 数组的大小。要获取未知大小数组的自有副本,必须将其转换为 Vec,这可以使用该to_vec()函数轻松完成。
let input = "some sample string".to_string();
let mut threads = vec![];
for chunk in input.chars().collect::<Vec<char>>().chunks(2) {
let owned_chunk = chunk.to_vec();
threads.push(thread::spawn({
move || -> () {
println!("{:?}", owned_chunk);
}
}))
}
Run Code Online (Sandbox Code Playgroud)
或者,由于我们知道数组的大小,因此我们可以在堆栈上创建一个数组来复制到其中。这消除了分配任何堆内存的需要。
let input = "some sample string".to_string();
let mut threads = vec![];
for chunk in input.chars().collect::<Vec<char>>().chunks(2) {
let mut owned_array = ['\0'; 2];
owned_array.copy_from_slice(chunk);
threads.push(thread::spawn({
move || -> () {
println!("{:?}", owned_array);
}
}))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4609 次 |
| 最近记录: |