如何匹配 Rust 中的数据类型? [英] How to match on data type in Rust?
问题描述
我正在尝试匹配结构的通用字段的数据类型并做出相应的反应.我的总体思路是这样的(代码无法编译):
I'm trying to match on the datatype of a generic field of a struct and react accordingly. My general idea was like this (code doesn't compile):
struct Foo<T> {
bar: T,
}
fn main() {
let x = Foo::<String> {
bar: "world".to_string(),
};
match x.bar {
String => println!("It's a string!"),
u32 => println!("It's a u32!"),
_ => println!("Something else"),
};
println!("end of program!");
}
来自编译器的错误信息:
The error message from the compiler:
warning: unreachable pattern
--> src/main.rs:12:9
|
11 | String => println!("It's a string!"),
| ------ matches any value
12 | u32 => println!("It's a u32!"),
| ^^^ unreachable pattern
|
= note: `#[warn(unreachable_patterns)]` on by default
warning: unreachable pattern
--> src/main.rs:13:9
|
11 | String => println!("It's a string!"),
| ------ matches any value
12 | u32 => println!("It's a u32!"),
13 | _ => println!("Something else"),
| ^ unreachable pattern
warning: unused variable: `String`
--> src/main.rs:11:9
|
11 | String => println!("It's a string!"),
| ^^^^^^ help: consider prefixing with an underscore: `_String`
|
= note: `#[warn(unused_variables)]` on by default
warning: unused variable: `u32`
--> src/main.rs:12:9
|
12 | u32 => println!("It's a u32!"),
| ^^^ help: consider prefixing with an underscore: `_u32`
warning: variable `String` should have a snake case name
--> src/main.rs:11:9
|
11 | String => println!("It's a string!"),
| ^^^^^^ help: convert the identifier to snake case: `string`
|
= note: `#[warn(non_snake_case)]` on by default
我想要的是 x
匹配第一个.我其实也不确定自己想做的事情能不能做,但是怎样才能达到预期的效果?
What I wanted was for x
to match the first one. I'm actually not sure what I want to do can be done, but what would achieve the desired effect?
推荐答案
Idiomatic Solution
创建一个特征来约束Foo
中的参数T
,将任何特定行为实现为该特征的关联函数.
Create a trait which constrains the parameter T
in Foo
, implement any specific behavior as an associated function of this trait.
示例:
trait PrintMe {
fn print_me(&self);
}
impl PrintMe for String {
fn print_me(&self) { println!("I am a string"); }
}
struct Foo<T: PrintMe> {
bar: T
}
fn main() {
// ...
x.bar.print_me();
}
这是有原则的泛型编程,您可以准确地声明可能的泛型参数的行为差异,这样就不会感到意外.
This is principled generic programming, where you declare exactly the difference of behavior of the possible generic parameters, so that there is no surprise.
另见:
准确的解决方案
Rust 确实可以查询类型:每种类型都有唯一的TypeId
相关联,您可以将 TypeId
与一系列 if
检查进行匹配.它很笨重.
Rust can indeed query types: each type has a unique TypeId
associated, and you can match on TypeId
with a series of if
checks. It's clunky.
fn print_me<T>(x: &Foo<T>) {
if TypeId::of::<T>() == TypeId::of::<String>() {
println!("I am a string");
} else // ...
}
但是请...不要那样做:)
But please... don't do that :)
这篇关于如何匹配 Rust 中的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!