gpt4 book ai didi

rust - Rust:论点要求借用持续于 `' static`

转载 作者:行者123 更新时间:2023-12-03 11:44:48 25 4
gpt4 key购买 nike

我正在使用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);
}
}))
}
当我尝试运行它时,出现以下错误:
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`

我知道编译器不知道线程中的块是否不会超过 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);
}
}))
}
另外,由于 我们知道数组的大小,因此我们可以在堆栈上创建要复制到的数组。这消除了分配任何堆内存的需要。
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);
}
}))
}

关于rust - Rust:论点要求借用持续于 `' static`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63654640/

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