Rust:如何与 Any 匹配
我想将任何类型存储在 Vec 中,并与存储在 Vec 中的实际类型进行匹配。
这是我的尝试:
use std::any::Any;
fn main() {
let mut a = Vec::<Box<dyn Any>>::new();
a.push(Box::new(42));
a.push(Box::new("hello"));
a.push(Box::new(99));
for n in a {
let type_id = (&*n).type_id();
println!("{type_id:?}");
match n {
i32 => println!("i32"),
str => println!("str"),
_ => println!("unhandled type")
}
}
}
但是,这总是打印“i32”,并且我收到无法访问的模式警告。
我如何与 Any 匹配?
I would like to store any type in a Vec, and match against the actual type that is stored in the Vec.
Here is my attempt:
use std::any::Any;
fn main() {
let mut a = Vec::<Box<dyn Any>>::new();
a.push(Box::new(42));
a.push(Box::new("hello"));
a.push(Box::new(99));
for n in a {
let type_id = (&*n).type_id();
println!("{type_id:?}");
match n {
i32 => println!("i32"),
str => println!("str"),
_ => println!("unhandled type")
}
}
}
However this always prints "i32", and I get an unreachable pattern warning.
How do I match against Any?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法匹配类型本身,但您可以使用
任何::is
:游乐场
You cannot match the type per se, but you can ask if it is of any specific type with
Any::is
:Playground
在您的示例中,
i32
和str
充当“标识符”(即变量名称),而不是类型。要使用
Any
,通常使用downcast_*
。例如:如果不关心包含的值,也可以使用
any.is::()
In your example,
i32
andstr
are acting as "identifiers" (i.e. variable names), rather than types.To work with
Any
, you generally usedowncast_*
. For example:If you don't care about the contained value, you can also use
any.is::<T>()