提交 e42db618 编写于 作者: J jackymao

add conversion

上级 8cef2014
......@@ -2,7 +2,9 @@
"node_id": "rust-81f36b5f17794dbb973c951ba06e01ea",
"keywords": [],
"children": [],
"export": [],
"export": [
"conversion.json"
],
"keywords_must": [],
"keywords_forbid": []
}
\ No newline at end of file
{
"type": "code_options",
"author": "jackymao_com",
"source": "conversion.md",
"notebook_enable": false,
"exercise_id": ""
}
\ No newline at end of file
# 类型转换
Rust 是静态类型语言,就是说,它的变量类型一旦明确之后就是固定的,不会再改变。 (shadowing 另说,因为shadowing 本质上定义了另外一个变量,只不过跟前面那个变量同名)
这导致在 Rust 中,类型的转化没有动态语言那么随心所欲。
Rust 类型转换方式主要有 casting (使用 as 语法), to_string(), From 和 Into (以及 try_from 和 try_into), 再就是手写转换(相当于写一个函数,输入的是一种类型,手工构建另一种类型返回)
问答:下面的代码转出的类型是:
```rust
fn main() {
let a = 42.0_f64 as f32 as i32 as i16;
use std::cell::UnsafeCell;
let five = &UnsafeCell::new(5) as *const UnsafeCell<i32> as *const i32 as *mut i32;
println!("{}, {}", get_type_name(&a), get_type_name(&five));
}
fn get_type_name<T:?Sized>(_:&T) -> &str {
std::any::type_name::<T>()
}
```
## 答案
i16, *mut i32
## 选项
###
f64, &UnsafeCell<i64>
###
f32, *const UnsafeCell<i32>
###
i32, *const i32
ref:
https://doc.rust-lang.org/std/any/fn.type_name.html
https://doc.rust-lang.org/src/core/cell.rs.html
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册