Rust:如何与 Any 匹配

发布于 2025-01-12 22:41:39 字数 567 浏览 3 评论 0原文

我想将任何类型存储在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小ぇ时光︴ 2025-01-19 22:41:39

您无法匹配类型本身,但您可以使用 任何::is:

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:?}");
        if n.is::<i32>() {
            println!("i32")
        } else if n.is::<&str>(){
            println!("str")
        } else {
            println!("unhandled type")
        }
    }
}

游乐场

You cannot match the type per se, but you can ask if it is of any specific type with Any::is:

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:?}");
        if n.is::<i32>() {
            println!("i32")
        } else if n.is::<&str>(){
            println!("str")
        } else {
            println!("unhandled type")
        }
    }
}

Playground

网白 2025-01-19 22:41:39

在您的示例中,i32str 充当“标识符”(即变量名称),而不是类型。

要使用 Any,通常使用 downcast_*。例如:

fn handle(any: Box<dyn Any>) {
  if let Some(s) = any.downcast_ref::<String>() {
    println!("found a string: {}", s);
  }

  if let Some(i) = any.downcast_ref::<i32>() {
    println!("found an int: {}", i);
  }
}

如果不关心包含的值,也可以使用any.is::()

In your example, i32 and str are acting as "identifiers" (i.e. variable names), rather than types.

To work with Any, you generally use downcast_*. For example:

fn handle(any: Box<dyn Any>) {
  if let Some(s) = any.downcast_ref::<String>() {
    println!("found a string: {}", s);
  }

  if let Some(i) = any.downcast_ref::<i32>() {
    println!("found an int: {}", i);
  }
}

If you don't care about the contained value, you can also use any.is::<T>()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文