# 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`。

## 匯入

```rust
use std::any::{Any, TypeId, type_name};
```

## 常用 API

### dyn Any 與 is：檢查型別

把值的參考轉成 `&dyn Any` 就抹除了具體型別。`is::<T>()` 回傳它是否剛好是 `T`。注意必須是**完全相同**的型別：`i32` 不等於 `i64`，`String` 不等於 `&str`。

簽名：
```rust
impl dyn Any {
    pub fn is<T: Any>(&self) -> bool
}
```

範例：
```rust
use std::any::Any;

fn kind(v: &dyn Any) -> &'static str {
    if v.is::<i32>() {
        "i32"
    } else if v.is::<String>() {
        "String"
    } else if v.is::<&str>() {
        "&str"
    } else {
        "其他"
    }
}

fn main() {
    println!("{}", kind(&7));
    println!("{}", kind(&String::from("hi")));
    println!("{}", kind(&"hi"));
    println!("{}", kind(&7i64));
}
```

輸出：
```text
i32
String
&str
其他
```

### downcast_ref：轉回具體型別的參考

`downcast_ref::<T>()` 成功時回傳 `Some(&T)`，型別不符時回傳 `None`，不會 panic。這是最常用的方式：一次完成檢查與轉換。

簽名：
```rust
impl dyn Any {
    pub fn downcast_ref<T: Any>(&self) -> Option<&T>
}
```

範例：
```rust
use std::any::Any;

fn show(items: &[Box<dyn Any>]) {
    for item in items {
        if let Some(n) = item.downcast_ref::<i32>() {
            println!("整數 {n}");
        } else if let Some(s) = item.downcast_ref::<String>() {
            println!("字串 {s}");
        } else if let Some(b) = item.downcast_ref::<bool>() {
            println!("布林 {b}");
        } else {
            println!("不認得的型別");
        }
    }
}

fn main() {
    let items: Vec<Box<dyn Any>> = vec![
        Box::new(42),
        Box::new(String::from("Rust")),
        Box::new(true),
        Box::new(3.5f64),
    ];
    show(&items);
}
```

輸出：
```text
整數 42
字串 Rust
布林 true
不認得的型別
```

### downcast_mut：轉回可變參考

和 `downcast_ref` 相同，但取得 `&mut T`，可以就地修改被抹除型別的值。

簽名：
```rust
impl dyn Any {
    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T>
}
```

範例：
```rust
use std::any::Any;

fn bump(v: &mut dyn Any) {
    if let Some(n) = v.downcast_mut::<u32>() {
        *n += 1;
    } else if let Some(list) = v.downcast_mut::<Vec<&'static str>>() {
        list.push("新項目");
    }
}

fn main() {
    let mut count: u32 = 9;
    let mut todo: Vec<&'static str> = vec!["買菜"];
    bump(&mut count);
    bump(&mut todo);
    println!("{count}");
    println!("{:?}", todo);
}
```

輸出：
```text
10
["買菜", "新項目"]
```

### 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](/pkg-thread)。

簽名：
```rust
impl<A: Allocator> Box<dyn Any, A> {
    pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Box<dyn Any, A>>
}
```

範例：
```rust
use std::any::Any;

fn main() {
    let boxed: Box<dyn Any> = Box::new(String::from("所有權回來了"));
    match boxed.downcast::<i32>() {
        Ok(n) => println!("是 i32：{n}"),
        Err(original) => {
            println!("不是 i32，再試 String");
            match original.downcast::<String>() {
                Ok(s) => {
                    let mut owned: String = *s;
                    owned.push('!');
                    println!("{owned}");
                }
                Err(_) => println!("也不是 String"),
            }
        }
    }
}
```

輸出：
```text
不是 i32，再試 String
所有權回來了!
```

### TypeId：型別的唯一識別碼

`TypeId::of::<T>()` 回傳代表 `T` 的識別碼，可以比較相等、可以當 `HashMap` 的鍵。常用來實作「每種型別存一份」的容器。`dyn Any` 也有 `type_id()` 方法取得內部值的 `TypeId`。

注意：`TypeId` 的實際數值在不同編譯之間可能不同，只能拿來比較，不要存檔或印出來依賴。

簽名：
```rust
impl TypeId {
    pub const fn of<T: ?Sized + 'static>() -> TypeId
}
```

範例：
```rust
use std::any::{Any, TypeId};
use std::collections::HashMap;

struct Registry {
    items: HashMap<TypeId, Box<dyn Any>>,
}

impl Registry {
    fn insert<T: Any>(&mut self, value: T) {
        self.items.insert(TypeId::of::<T>(), Box::new(value));
    }
    fn get<T: Any>(&self) -> Option<&T> {
        self.items.get(&TypeId::of::<T>())?.downcast_ref::<T>()
    }
}

struct Port(u16);
struct Host(String);

fn main() {
    let mut reg = Registry { items: HashMap::new() };
    reg.insert(Port(8080));
    reg.insert(Host(String::from("localhost")));
    reg.insert(Port(3000));

    println!("port = {}", reg.get::<Port>().map(|p| p.0).unwrap_or(0));
    println!("host = {}", reg.get::<Host>().map(|h| h.0.as_str()).unwrap_or("-"));
    println!("有 bool? {}", reg.get::<bool>().is_some());
    println!("{}", TypeId::of::<Port>() == (&Port(1) as &dyn Any).type_id());
}
```

輸出：
```text
port = 3000
host = localhost
有 bool? false
true
```

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

### type_name 與 type_name_of_val：取得型別名稱

`type_name::<T>()` 回傳型別名稱字串，`type_name_of_val(&v)`（Rust 1.76 起）從值推導。適合除錯訊息與日誌。

注意：回傳的字串格式沒有穩定保證，未來版本可能改變，不要拿它做邏輯判斷；判斷型別請用 `TypeId` 或 `downcast_ref`。

簽名：
```rust
pub const fn type_name<T: ?Sized>() -> &'static str
pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str
```

範例：
```rust
use std::any::{type_name, type_name_of_val};

fn debug_len<T>(items: &[T]) {
    println!("{} 個 {}", items.len(), type_name::<T>());
}

fn main() {
    debug_len(&[1u8, 2, 3]);
    debug_len(&["a", "b"]);
    let pair = (1.5f32, 'x');
    println!("{}", type_name_of_val(&pair));
    println!("{}", type_name::<Option<String>>());
}
```

輸出：
```text
3 個 u8
2 個 &str
(f32, char)
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` 只給人看，格式不保證穩定
