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 }
    }
}
相关推荐
NutShell Wang2 小时前
Rust 1.97 实战迁移:v0 符号重整、Cargo 警告治理与位运算新 API
人工智能·后端·性能优化·rust·vibe coding
进哥AI研习社2 小时前
AtomCode 源码编译与二次开发入门:从 Clone 仓库到自定义 Agent 工具的完整指南
rust·二次开发·源码编译·atomcode·agent 工具·tool 扩展·ai 编码智能体
程序员爱钓鱼4 小时前
Rust 泛型 Generics详解:编写可复用且类型安全的代码
后端·面试·rust
SomeB1oody17 小时前
【RustyML入门】6.0. 数学工具
开发语言·后端·机器学习·rust·教程
今天AI了吗1 天前
从聊天到委派:AI Agent 如何推进长期任务
数据库·人工智能·python·sql·rust
梦醒沉醉1 天前
std1.97.1——fmt模块总览
rust
SomeB1oody1 天前
【RustyML入门】5.3. 聚类指标
开发语言·后端·机器学习·rust·教程
雾沉川1 天前
Rust IDE 选型:除 VS Code 之外,RustRover 非商业场景可免费使用
ide·vscode·rust
特立独行的猫a1 天前
Rust + Tauri实现一棵「习惯树」:创意应用 从 Grove 的灵感说起
开发语言·后端·rust·tauri·习惯树·创意应用
程序员爱钓鱼1 天前
Go 编程实战:Map——使用 Key-Value 管理键值数据
后端·rust·go