英文:
cannot be built from an iterator over elements of type `()`
问题
这个程序用于打印并行运行的线程。在结束线程之前打印所有启动线程。但是这个程序抛出了错误 the trait
FromIterator<()> is not implemented for Vec<JoinHandle<>> the trait FromIterator<T> is implemented for Vec<T>
。这个程序有什么问题?任何反馈都会很有帮助。
let handles: Vec<JoinHandle<String>> = (0..=10).map(|i| {
let delay = rand::thread_rng().gen_range(10..=2000);
let builder =
thread::Builder::new().name(format!("Thread-{}", i));
builder.spawn(move || {
println!(
"thread started = {}",
thread::current().name().unwrap()
);
thread::sleep(Duration::from_millis(delay));
thread::current().name().unwrap().to_owned()
}).unwrap();
}).collect();
for h in handles {
let r = h.join().unwrap();
println!("thread done = {:?}", r);
}
英文:
This program is for printing parallel running thread. Print all start thread before end thread. But this program throw error the trait
FromIterator<()> is not implemented for Vec<JoinHandle<>> the trait FromIterator<T> is implemented for Vec<T>
. What's wrong with this program? Any feedback helps a lot.
let handles: Vec<JoinHandle<String>> = (0..=10).map(|i| {
let delay = rand::thread_rng().gen_range(10..=2000);
let builder =
thread::Builder::new().name(format!("Thread-{}", i));
builder.spawn(move || {
println!(
"thread started = {}",
thread::current().name().unwrap()
);
thread::sleep(Duration::from_millis(delay));
thread::current().name().unwrap().to_owned()
}).unwrap();
}).collect();
for h in handles {
let r = h.join().unwrap();
println!("thread done = {:?}", r);
}
答案1
得分: 1
如果你希望函数的最后一个值(无论是顶层函数还是闭包)被隐式返回,你 不应该 以分号结尾。分号终止正在运行以产生效果的语句,而不是返回函数的最终表达式。请将以下代码替换为:
builder.spawn(move || {
...
}).unwrap() // <- 没有分号 :)
英文:
If you want the last value of a function (be it a top-level function or a closure) to be returned implicitly, you should not end it with a semicolon. Semicolons terminate statements that are being run for effects, not the final expression of a returning function. Replace
builder.spawn(move || {
...
}).unwrap();
with
builder.spawn(move || {
...
}).unwrap() // <- No semicolon :)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论