std::any

最後更新


在執行期查詢與轉換型別:把值當成「任意型別」存放,之後再檢查它到底是什麼。

這個模組做什麼


Rust 的型別通常在編譯期就確定。但有時候你需要一個容器裝「各種型別的值」,例如外掛系統的設定、事件匯流排的訊息、panic 時攜帶的錯誤內容。std::any 提供:
名稱用途
Any 特徵(trait)所有 'static 型別自動實作,可透過 dyn Any 抹除型別
downcast_ref / downcast_mut從 &dyn Any 嘗試轉回具體型別的參考
Box<dyn Any>::downcast從 Box<dyn Any> 取回具體型別的所有權
TypeId型別的唯一識別碼,可比較、可當映射的鍵
type_name取得型別名稱字串,供除錯用

和 enum 的差別:如果可能的型別是有限且已知的,用 enum 更清楚、更快;Any 適合型別集合在寫程式庫時無法預知的情況。
注意:Any 只適用於 'static 型別,也就是不含非 'static 借用的型別;&'a str('a 不是 'static)不能轉成 dyn Any。

匯入


  1. use std::any::{Any, TypeId, type_name};

常用 API


dyn Any 與 is:檢查型別


把值的參考轉成 &dyn Any 就抹除了具體型別。is::<T>() 回傳它是否剛好是 T。注意必須是完全相同的型別:i32 不等於 i64,String 不等於 &str。
簽名:
  1. impl dyn Any {
  2. pub fn is<T: Any>(&self) -> bool
  3. }

範例:
  1. use std::any::Any;
  2. fn kind(v: &dyn Any) -> &'static str {
  3. if v.is::<i32>() {
  4. "i32"
  5. } else if v.is::<String>() {
  6. "String"
  7. } else if v.is::<&str>() {
  8. "&str"
  9. } else {
  10. "其他"
  11. }
  12. }
  13. fn main() {
  14. println!("{}", kind(&7));
  15. println!("{}", kind(&String::from("hi")));
  16. println!("{}", kind(&"hi"));
  17. println!("{}", kind(&7i64));
  18. }

輸出:
  1. i32
  2. String
  3. &str
  4. 其他

downcast_ref:轉回具體型別的參考


downcast_ref::<T>() 成功時回傳 Some(&T),型別不符時回傳 None,不會 panic。這是最常用的方式:一次完成檢查與轉換。
簽名:
  1. impl dyn Any {
  2. pub fn downcast_ref<T: Any>(&self) -> Option<&T>
  3. }

範例:
  1. use std::any::Any;
  2. fn show(items: &[Box<dyn Any>]) {
  3. for item in items {
  4. if let Some(n) = item.downcast_ref::<i32>() {
  5. println!("整數 {n}");
  6. } else if let Some(s) = item.downcast_ref::<String>() {
  7. println!("字串 {s}");
  8. } else if let Some(b) = item.downcast_ref::<bool>() {
  9. println!("布林 {b}");
  10. } else {
  11. println!("不認得的型別");
  12. }
  13. }
  14. }
  15. fn main() {
  16. let items: Vec<Box<dyn Any>> = vec![
  17. Box::new(42),
  18. Box::new(String::from("Rust")),
  19. Box::new(true),
  20. Box::new(3.5f64),
  21. ];
  22. show(&items);
  23. }

輸出:
  1. 整數 42
  2. 字串 Rust
  3. 布林 true
  4. 不認得的型別

downcast_mut:轉回可變參考


和 downcast_ref 相同,但取得 &mut T,可以就地修改被抹除型別的值。
簽名:
  1. impl dyn Any {
  2. pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T>
  3. }

範例:
  1. use std::any::Any;
  2. fn bump(v: &mut dyn Any) {
  3. if let Some(n) = v.downcast_mut::<u32>() {
  4. *n += 1;
  5. } else if let Some(list) = v.downcast_mut::<Vec<&'static str>>() {
  6. list.push("新項目");
  7. }
  8. }
  9. fn main() {
  10. let mut count: u32 = 9;
  11. let mut todo: Vec<&'static str> = vec!["買菜"];
  12. bump(&mut count);
  13. bump(&mut todo);
  14. println!("{count}");
  15. println!("{:?}", todo);
  16. }

輸出:
  1. 10
  2. ["買菜", "新項目"]

Box<dyn Any>::downcast:取回所有權


downcast_ref 只能借用;若要把值從 Box<dyn Any> 取出,用 downcast::<T>()。成功回傳 Ok(Box<T>),失敗則把原本的 Box<dyn Any> 放在 Err 裡還給你,值不會遺失。執行緒 panic 後 join() 拿到的 Box<dyn Any + Send> 也用同樣方法讀出 panic 訊息,見 std::thread。
簽名:
  1. impl<A: Allocator> Box<dyn Any, A> {
  2. pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Box<dyn Any, A>>
  3. }

範例:
  1. use std::any::Any;
  2. fn main() {
  3. let boxed: Box<dyn Any> = Box::new(String::from("所有權回來了"));
  4. match boxed.downcast::<i32>() {
  5. Ok(n) => println!("是 i32:{n}"),
  6. Err(original) => {
  7. println!("不是 i32,再試 String");
  8. match original.downcast::<String>() {
  9. Ok(s) => {
  10. let mut owned: String = *s;
  11. owned.push('!');
  12. println!("{owned}");
  13. }
  14. Err(_) => println!("也不是 String"),
  15. }
  16. }
  17. }
  18. }

輸出:
  1. 不是 i32,再試 String
  2. 所有權回來了!

TypeId:型別的唯一識別碼


TypeId::of::<T>() 回傳代表 T 的識別碼,可以比較相等、可以當 HashMap 的鍵。常用來實作「每種型別存一份」的容器。dyn Any 也有 type_id() 方法取得內部值的 TypeId。
注意:TypeId 的實際數值在不同編譯之間可能不同,只能拿來比較,不要存檔或印出來依賴。
簽名:
  1. impl TypeId {
  2. pub const fn of<T: ?Sized + 'static>() -> TypeId
  3. }

範例:
  1. use std::any::{Any, TypeId};
  2. use std::collections::HashMap;
  3. struct Registry {
  4. items: HashMap<TypeId, Box<dyn Any>>,
  5. }
  6. impl Registry {
  7. fn insert<T: Any>(&mut self, value: T) {
  8. self.items.insert(TypeId::of::<T>(), Box::new(value));
  9. }
  10. fn get<T: Any>(&self) -> Option<&T> {
  11. self.items.get(&TypeId::of::<T>())?.downcast_ref::<T>()
  12. }
  13. }
  14. struct Port(u16);
  15. struct Host(String);
  16. fn main() {
  17. let mut reg = Registry { items: HashMap::new() };
  18. reg.insert(Port(8080));
  19. reg.insert(Host(String::from("localhost")));
  20. reg.insert(Port(3000));
  21. println!("port = {}", reg.get::<Port>().map(|p| p.0).unwrap_or(0));
  22. println!("host = {}", reg.get::<Host>().map(|h| h.0.as_str()).unwrap_or("-"));
  23. println!("有 bool? {}", reg.get::<bool>().is_some());
  24. println!("{}", TypeId::of::<Port>() == (&Port(1) as &dyn Any).type_id());
  25. }

輸出:
  1. port = 3000
  2. host = localhost
  3. 有 bool? false
  4. true

第二次插入 Port 覆蓋了第一次,因為兩者的 TypeId 相同。

type_name 與 type_name_of_val:取得型別名稱


type_name::<T>() 回傳型別名稱字串,type_name_of_val(&v)(Rust 1.76 起)從值推導。適合除錯訊息與日誌。
注意:回傳的字串格式沒有穩定保證,未來版本可能改變,不要拿它做邏輯判斷;判斷型別請用 TypeId 或 downcast_ref。
簽名:
  1. pub const fn type_name<T: ?Sized>() -> &'static str
  2. pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str

範例:
  1. use std::any::{type_name, type_name_of_val};
  2. fn debug_len<T>(items: &[T]) {
  3. println!("{} 個 {}", items.len(), type_name::<T>());
  4. }
  5. fn main() {
  6. debug_len(&[1u8, 2, 3]);
  7. debug_len(&["a", "b"]);
  8. let pair = (1.5f32, 'x');
  9. println!("{}", type_name_of_val(&pair));
  10. println!("{}", type_name::<Option<String>>());
  11. }

輸出:
  1. 3 個 u8
  2. 2 個 &str
  3. (f32, char)
  4. core::option::Option<alloc::string::String>

重點整理


  • Any 讓 'static 型別在執行期被抹除再還原,適合型別集合無法預知的情境;型別已知就用 enum
  • downcast_ref / downcast_mut 失敗回傳 None,Box::downcast 失敗把原值放回 Err,都不會 panic
  • 型別比對要求完全相同:i32 與 i64、String 與 &str 都不一樣
  • TypeId 可當映射鍵做「每型別一份」的容器,但數值不穩定,只能比較
  • type_name 只給人看,格式不保證穩定