下面的代码运行正确。
{
let a = &mut 3;
*a = 4;
assert_eq!(*a, 4);
}
Run Code Online (Sandbox Code Playgroud)
以下也运行。
{
let a = Some(&3);
let mut b = a.unwrap();
assert_eq!(a.unwrap(), &3);
}
Run Code Online (Sandbox Code Playgroud)
但以下内容无法编译。
{
let a = Some(&mut 3);
assert_eq!(*a.unwrap(), 3);
}
Run Code Online (Sandbox Code Playgroud)
错误是:
40 | let a = Some(&mut 3);
| ^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
41 | assert_eq!(*a.unwrap(), 3);
| - borrow later used …Run Code Online (Sandbox Code Playgroud) 我们可以使用std::any::Any将不同类型收集到一个Box.
use std::any::Any;
fn foo(value: Box<dyn Any>) {
if let Some(string) = value.downcast_ref::<String>() {
println!("String: {}", *string);
} else if let Some(int) = value.downcast_ref::<i32>() {
println!("i32: {}", *int);
}
}
fn main() {
let x = Box::new("hello".to_owned());
let y = Box::new(123);
foo(x);
foo(y);
}
Run Code Online (Sandbox Code Playgroud)
我们还可以用来downcast识别 a 中值的类型Box。我了解到C++中的类型可以通过虚函数来确定,根据这个问题,RTTI是如何工作的?。然而,类似的类型i32在 Rust 中也可以被向下转型。它是如何工作的?
rust ×2