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 小时前
编程语言全指南:从C到Rust
java·c语言·开发语言·c++·python·rust·c#
亿牛云爬虫专家2 小时前
学术文献爬虫 OOM 崩溃与 403 风暴
爬虫·rust·爬虫代理·403·oom killer·学术文献·403 forbidden
土豆125013 小时前
Tauri 入门与实践:用 Rust 构建你的下一个桌面应用
前端·rust
土豆125014 小时前
Rust 错误处理实战:anyhow + thiserror 的黄金搭档
rust
Zarek枫煜15 小时前
C3 编程语言 - 现代 C 的进化之选
c语言·开发语言·青少年编程·rust·游戏引擎
咚为21 小时前
Rust 经典面试题255道
开发语言·面试·rust
@atweiwei1 天前
用 Rust 构建 LLM 应用的高性能框架
开发语言·后端·ai·rust·langchain·llm
chrislearn1 天前
Salvo 为什么不采用宏式路由
rust
Amos_Web2 天前
Solana开发(1)- 核心概念扫盲篇&&扫雷篇
前端·rust·区块链
golang学习记2 天前
VS Code官宣:全面支持Rust!
开发语言·vscode·后端·rust