小编fls*_*fls的帖子

为什么这些创建引用的方式表现不同?

下面的代码运行正确。

{
    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)

rust

5
推荐指数
1
解决办法
152
查看次数

为什么 i32 Box 类型可以在 Rust 中向下转型?

我们可以使用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
推荐指数
1
解决办法
110
查看次数

标签 统计

rust ×2