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 }
    }
}
相关推荐
脱胎换骨-军哥8 小时前
C++/Rust无缝互操作:混合系统新常态
开发语言·c++·rust
songroom8 小时前
Kimi K3:Rust封装XTP接口详细教程实践
开发语言·后端·rust
独孤留白14 小时前
从C到Rust:Trait From Into 类型转换
rust
doiito15 小时前
【RUST AI】把 TTS 搬进浏览器:kokoroi-rs 的 WASM 实践
ai·rust·架构设计
jinshw15 小时前
自己实现GIS配图软件(一)
rust·开源·gis
程序员爱钓鱼16 小时前
Rust 元组 Tuple 详解:组合不同类型的数据
前端·后端·rust
humbinal2 天前
同时支持 gui & cli 的 parquet 文件查看工具,高性能小清新!
hive·python·rust·spark·开源·github·parquet
belowfrog2 天前
Rust 的 Deref 到底为啥这么乱呀!
rust
程序员爱钓鱼2 天前
Rust 数组 Array 详解:定义、访问、遍历与切片
后端·rust
程序员爱钓鱼3 天前
Rust if let 与 while let 详解:简化模式匹配
前端·后端·rust