本文簡要介紹rust語言中 std::any::Any.downcast_ref
的用法。
用法
pub fn downcast_ref<T>(&self) -> Option<&T> where T: Any,
如果它是類型 T
,則返回對裝箱值的一些引用,如果不是,則返回 None
。
例子
use std::any::Any;
fn print_if_string(s: &dyn Any) {
if let Some(string) = s.downcast_ref::<String>() {
println!("It's a string({}): '{}'", string.len(), string);
} else {
println!("Not a string...");
}
}
print_if_string(&0);
print_if_string(&"cookie monster".to_string());
相關用法
- Rust Any.downcast_mut用法及代碼示例
- Rust Any.is用法及代碼示例
- Rust Any.type_id用法及代碼示例
- Rust Ancestors用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust AtomicPtr.compare_exchange_weak用法及代碼示例
- Rust AsFd.as_fd用法及代碼示例
- Rust AtomicU32.fetch_min用法及代碼示例
- Rust AtomicI8.fetch_or用法及代碼示例
- Rust AtomicI8.as_mut_ptr用法及代碼示例
- Rust AtomicU8.fetch_or用法及代碼示例
- Rust AtomicUsize.load用法及代碼示例
- Rust AtomicI16.fetch_min用法及代碼示例
- Rust AtomicI16.fetch_and用法及代碼示例
- Rust AtomicU16.into_inner用法及代碼示例
- Rust AtomicI16.fetch_nand用法及代碼示例
- Rust AtomicI32.compare_exchange用法及代碼示例
- Rust AtomicU16.from_mut用法及代碼示例
- Rust AtomicI16.swap用法及代碼示例
- Rust AtomicU8.as_mut_ptr用法及代碼示例
- Rust AtomicBool.fetch_update用法及代碼示例
- Rust AtomicU32.fetch_max用法及代碼示例
- Rust AtomicI64.from_mut用法及代碼示例
- Rust Arc.assume_init用法及代碼示例
- Rust AtomicI32.fetch_and用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::any::Any.downcast_ref。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。