gpt4 book ai didi

rust - 为什么 `ToString` 项的迭代器要求它们也为 `Display`?

转载 作者:行者123 更新时间:2023-12-05 04:26:35 24 4
gpt4 key购买 nike

以下代码:

enum MyEnum {
A,
B,
}

impl ToString for MyEnum {
fn to_string(&self) -> String {
match *self {
Self::A => format!("A"),
Self::B => format!("B"),
}
}
}

pub fn foo<I: ToString>(item: I) {
println!("item: {}", item.to_string());
}

pub fn bar<I: ToString>(iter: impl Iterator<Item = I>) {
iter.for_each(|item| println!("item: {}", item.to_string()))
}

fn main() {
foo(MyEnum::A);
bar([MyEnum::A, MyEnum::B].iter());
}

产生以下编译错误:

error[E0277]: `MyEnum` doesn't implement `std::fmt::Display`
--> src\bin\main6.rs:25:2
|
25 | bar([MyEnum::A, MyEnum::B].iter());
| ^^^ `MyEnum` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `MyEnum`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required because of the requirements on the impl of `std::fmt::Display` for `&MyEnum`
= note: required because of the requirements on the impl of `ToString` for `&MyEnum`
note: required by a bound in `bar`
--> src\bin\main6.rs:19:15
|
19 | pub fn bar<I: ToString>(iter: impl Iterator<Item = I>) {
| ^^^^^^^^ required by this bound in `bar`

For more information about this error, try `rustc --explain E0277`.

bar 接受其项实现 ToString 的迭代器。 MyEnum 实现了 ToString,所以 [MyEnum::A, MyEnum::B].iter() 实际上是一个迭代器ToString.

foobar 很相似,都是将泛型类型I 替换为MyEnum,所以为什么 bar 中需要特征绑定(bind) Displayfoo 中不需要?

最佳答案

[MyEnum::A, MyEnum::B].iter() 创建一个迭代器,其项为 &MyEnum&MyEnum 不实现 ToString,只有 MyEnum 实现。这有效:

enum MyEnum {
A,
B,
}

impl ToString for MyEnum {
fn to_string(&self) -> String {
match *self {
Self::A => format!("A"),
Self::B => format!("B"),
}
}
}

pub fn foo<I: ToString>(item: I) {
println!("item: {}", item.to_string());
}

pub fn bar<I: ToString>(iter: impl Iterator<Item = I>) {
iter.for_each(|item| println!("item: {}", item.to_string()))
}

fn main() {
foo(MyEnum::A);
bar([MyEnum::A, MyEnum::B].into_iter());
}

Playground

如果你想接受任何 &I 这样 I: Display:

pub fn bar<'a, I: 'a>(iter: impl Iterator<Item = &'a I>) where I: ToString {
iter.for_each(|item| println!("item: {}", item.to_string()))
}

关于rust - 为什么 `ToString` 项的迭代器要求它们也为 `Display`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73029305/

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