读了一些参考资料,可以知道有这么些个转化方式:
知识点
在 Rust 中,提供了多种方式进行类型转换。以下是总结的主要类型转换方式:
1. 类型强转 (as)
 
这是最简单的类型转换方式,使用 as 关键字来进行显式的类型转换。例如,将整数转换为浮点数:
println!("{}", 1 as f32 + 1.0);
2. From 和 Into
 
From 和 Into 是 Rust 标准库中提供的两种类型转换特质。From 用于从一种类型转换到另一种类型,而 Into 则是从一种类型转换到另一种类型。这两种特质通常是互为逆操作。例如:
let num: i32 = 5.into();
3. TryFrom 和 TryInto
 
TryFrom 和 TryInto 与 From 和 Into 类似,但它们用于那些转换可能会失败的情况。当转换可能失败时,可以使用 TryFrom 和 TryInto 来提供更细粒度的控制。例如:
let result: Result<i32, _> = "42".parse();
4. AsRef 和 AsMut
 
AsRef 和 AsMut 用于廉价的引用转换。AsRef 用于不可变引用的转换,而 AsMut 则用于可变引用的转换。例如:
let s = String::from("hello");
let str_slice: &str = s.as_ref();
5. FromStr
 
FromStr 是 std::str 模块中的一个特质,用于从字符串转换为目标类型。通常通过 parse 方法来实现这一转换。例如:
let person: Person = "Mark,20".parse().unwrap();
总结
Rust 提供了多种方式进行类型转换,主要包括:
- 类型强转 (as)
- From和- Into
- TryFrom和- TryInto
- AsRef和- AsMut
- FromStr
这些转换方式覆盖了从简单的类型转换到更复杂的、可能会失败的类型转换的各种情况。通过这些特质和操作符,Rust 提供了一种灵活的方式来处理不同类型之间的转换需求。希望这些信息能帮助你更好地理解和使用 Rust 中的类型转换。如果有任何其他问题或需要进一步的帮助,请随时提问。
参考资料
Type conversions
Rust offers a multitude of ways to convert a value of a given type into another type.
The simplest form of type conversion is a type cast expression. It is denoted with the binary operator as. For instance, println!("{}", 1 + 1.0); would not compile, since 1 is an integer while 1.0 is a float. However, println!("{}", 1 as f32 + 1.0) should compile. The exercise using_as tries to cover this.
Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the convert module.
 The traits are the following:
- Fromand- Intocovered in- from_into
- TryFromand- TryIntocovered in- try_from_into
- AsRefand- AsMutcovered in- as_ref_mut
Furthermore, the std::str module offers a trait called FromStr which helps with converting strings into target types via the parse method on strings. If properly implemented for a given type Person, then let p: Person = "Mark,20".parse().unwrap() should both compile and run without panicking.
These should be the main ways within the standard library to convert data into your desired types.
Further information
These are not directly covered in the book, but the standard library has a great documentation for it.
- conversions
- FromStrtrait