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 }
    }
}
相关推荐
云雾J视界20 分钟前
告别手动寄存器编程:STM32-RS 生态如何重构嵌入式开发效率
rust·svd·嵌入式开发·寄存器·工具链·可编译·社区驱动
Source.Liu16 小时前
【time-rs】月份枚举实现
rust·time
福大大架构师每日一题18 小时前
2025年12月TIOBE编程语言排行榜,Go语言排名第15,Rust语言排名17。编程语言 R 重返前十。
开发语言·后端·rust
苏 凉19 小时前
在 openEuler 24.03 LTS SP2 上安装部署 iSula 容器引擎及性能测试
开发语言·rust
ULTRA??20 小时前
字符串处理小写字母转换大写字母
c++·python·rust
ZC·Shou2 天前
Rust 之二 各组件工具的源码、构建、配置、使用(二)
开发语言·ide·rust·工具·命令·clippy·rustfmt
ULTRA??2 天前
Rust的移动语义
c++·算法·rust
熬了夜的程序员2 天前
【Rust学习之路】序
开发语言·后端·学习·rust
Mintopia2 天前
⚙️ 模型接口与微调兼容性:AIGC系统整合的底层心脏跳动
人工智能·架构·rust
ULTRA??2 天前
RUST是移动语义与copy trait
算法·rust