gpt4 book ai didi

rust - 如何将参数化枚举从泛型类型映射到另一个类型?

转载 作者:行者123 更新时间:2023-11-29 07:47:10 29 4
gpt4 key购买 nike

如果我有类似 MyEnum<T> 的类型,在并非每个变体都已参数化的情况下如何映射它?

例如,我想从 MyEnum<u32> 转换至 MyEnum<String> :

enum MyEnum<T> {
B,
C,
D(T),
}

fn trans(a: MyEnum<u32>) -> MyEnum<String> {
match a {
MyEnum::D(i) => MyEnum::D(i.to_string()),
other_cases => other_cases,
}
}

fn main() {}

这失败了:

error[E0308]: match arms have incompatible types
--> src/main.rs:8:9
|
8 | match a {
| ^ expected struct `std::string::String`, found u32
|
= note: expected type `MyEnum<std::string::String>`
= note: found type `MyEnum<u32>`
note: match arm with an incompatible type
--> src/main.rs:10:28
|
10 | other_cases => other_cases,
| ^^^^^^^^^^^

而不是 other_cases => other_cases行,我试过了,也没有成功:

other_cases => {
let o: MyEnum<String> = other_cases;
o
}

最佳答案

我会在您的枚举上创建一个 map 方法:

#[derive(Debug)]
enum MyEnum<T> {
B,
C,
D(T),
}

impl<T> MyEnum<T> {
fn map<U>(self, f: impl FnOnce(T) -> U) -> MyEnum<U> {
use MyEnum::*;

match self {
B => B,
C => C,
D(x) => D(f(x)),
}
}
}

fn main() {
let answer = MyEnum::D(42);
let answer2 = answer.map(|x| x.to_string());
println!("{:?}", answer2);
}

这类似于现有的 map 方法,例如 Option::map .

关于rust - 如何将参数化枚举从泛型类型映射到另一个类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31123882/

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