为什么Dbg在for_each循环中似乎不起作用?

时间:2019-07-25 21:58:25

标签: rust

为什么dbg!在此for_each循环中不起作用? Playground link

fn main() {
    let chars = "hello".chars();
    chars.clone().for_each(|x| dbg!(x));
}

我收到此编译错误:

error[E0308]: mismatched types
 --> src/main.rs:4:32
  |
4 |     chars.clone().for_each(|x| dbg!(x));
  |                                ^^^^^^^ expected (), found char
  |
  = note: expected type `()`
             found type `char`
  = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

我也尝试过传递对x的引用。

println的工作原理:

fn main() {
    let chars = "hello".chars();
    chars.clone().for_each(|x| println!("{:?}", x));
}

1 个答案:

答案 0 :(得分:3)

dbg!返回您传入的值,而for_each需要返回一个单位类型。 println!返回单位类型。

我们可以通过添加;来完成这项工作:

    chars.clone().for_each(|x| {dbg!(x);});