Rust- 类型转换

Rust is a statically typed language, which means that it emphasizes on knowing the types of all variables at compile time. The concept of type safety is very crucial in Rust, and the language provides several mechanisms for type conversion.

Type conversion in Rust is explicit, meaning that you need to specify the type you want to convert to.

Here are two common forms of type conversion in Rust:

  1. Casting : Rust uses the as keyword to perform basic casting between primitive types. For instance:

    rust 复制代码
    let num = 5.6;
    let integer: i32 = num as i32;  // `integer` will be 5

    It's important to note that casting with as can be unsafe, especially when casting between types of different sizes. For example, casting from a larger integer type to a smaller one (like from u32 to u8) can lead to data loss.

  2. From/Into Traits : The From and Into traits are used for more complex conversions. The From trait allows a type to define how to create itself from another type, while the Into trait is the reciprocal of the From trait.

    rust 复制代码
    let my_str = "5";
    let num: i32 = my_str.parse().unwrap();  // `num` will be 5

    In the above code, we used parse function which is based on the FromStr trait to convert a string slice into an i32.

    Similarly, we can use From/Into for user-defined conversions:

    rust 复制代码
    #[derive(Debug)]
    struct Number {
        value: i32,
    }
    
    impl From<i32> for Number {
        fn from(item: i32) -> Self {
            Number { value: item }
        }
    }
    
    fn main() {
        let num = Number::from(30);
        println!("My number is {:?}", num);
    }

    This example creates a Number struct from an i32 using the From trait.

In all these examples, type conversion is explicit and checked at compile time, adding to the safety and robustness of Rust.

rust 复制代码
fn main() {
    let s1 = "Rust";
    let s2 = String::from(s1);

    let my_number = MyNumber::from(1);
    println!("{:?}", my_number); // MyNumber { num: 1 }

    let spend = 3;
    let my_spend: MyNumber = spend.into();
    println!("{:?}", my_spend); // MyNumber { num: 3 }

    let cost: i32 = "5".parse().unwrap();
    println!("{}", cost);       // 5
}

#[derive(Debug)]
struct MyNumber {
    num: i32,
}

impl From<i32> for MyNumber {
    fn from(value: i32) -> Self {
        MyNumber { num: value }
    }
}
相关推荐
码码哈哈爱分享1 小时前
Tauri 框架介绍
css·rust·vue·html
寻月隐君20 小时前
硬核实战:从零到一,用 Rust 和 Axum 构建高性能聊天服务后端
后端·rust·github
m0_480502641 天前
Rust 入门 泛型和特征-特征对象 (十四)
开发语言·后端·rust
RustFS1 天前
如何用 Rust 对 RustFS MCP Server 进行扩展?
rust
我是前端小学生3 天前
一文梳理Rust语言中的可变结构体实例
rust
Source.Liu3 天前
【unitrix数间混合计算】2.21 二进制整数加法计算(bin_add.rs)
rust
Include everything3 天前
Rust学习笔记(二)|变量、函数与控制流
笔记·学习·rust
Source.Liu4 天前
【unitrix数间混合计算】2.20 比较计算(cmp.rs)
rust
许野平4 天前
Rust:构造函数 new() 如何进行错误处理?
开发语言·后端·rust