不能从一个元素类型为`()`的迭代器构建。

huangapple go评论63阅读模式
英文:

cannot be built from an iterator over elements of type `()`

问题

这个程序用于打印并行运行的线程。在结束线程之前打印所有启动线程。但是这个程序抛出了错误 the trait FromIterator<()> is not implemented for Vec&lt;JoinHandle&lt;&gt;&gt; the trait FromIterator&lt;T&gt; is implemented for Vec&lt;T&gt;。这个程序有什么问题?任何反馈都会很有帮助。

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);
}

rust-playground

英文:

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&lt;JoinHandle&lt;&gt;&gt; the trait FromIterator&lt;T&gt; is implemented for Vec&lt;T&gt;. What's wrong with this program? Any feedback helps a lot.

let handles: Vec&lt;JoinHandle&lt;String&gt;&gt; = (0..=10).map(|i| {
        let delay = rand::thread_rng().gen_range(10..=2000);
        let builder =
          thread::Builder::new().name(format!(&quot;Thread-{}&quot;, i));
        
        builder.spawn(move || {
          println!(
            &quot;thread started = {}&quot;,
            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!(&quot;thread done = {:?}&quot;, r);
}

rust-playground

答案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() // &lt;- No semicolon :)

huangapple
  • 本文由 发表于 2023年1月9日 11:17:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定