gpt4 book ai didi

rust - 为什么 Dbg 似乎不能在 for_each 循环中工作?

转载 作者:行者123 更新时间:2023-11-29 08:24:18 25 4
gpt4 key购买 nike

为什么 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));
}

最佳答案

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

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

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

关于rust - 为什么 Dbg 似乎不能在 for_each 循环中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57210634/

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