Rust- 类型转换

这篇具有很好参考价值的文章主要介绍了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:

    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.

    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:

    #[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.文章来源地址https://www.toymoban.com/news/detail-619966.html

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 }
    }
}

到了这里,关于Rust- 类型转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Rust教程:How to Rust-基本类型

    本专栏是优质Rust技术专栏,推荐精通一门技术栈的蟹友,不建议完全无计算机基础的同学 感谢Rust圣经开源社区的同学,为后来者提供了非常优秀的Rust学习资源 本文使用: 操作系统macOS Sonoma 14 / Apple M1 编译器:Rustc Cargo 感谢一路相伴的朋友们,感谢你们的支持 ^ _ ^ Rust教

    2024年04月12日
    浏览(32)
  • 深入理解Rust基本类型

       团队博客: 汽车电子社区   Rust基本类型有如下几种:     1、 数值类型 : 有符号整数 (i8, i16, i32, i64, isize)、 无符号整数 (u8, u16, u32, u64, usize) 、浮点数 (f32, f64)、以及有理数、复数。     2、 字符串 :字符串字面量和字符串切片 str。     3、 布尔类型 :

    2024年01月20日
    浏览(38)
  • Rust 原生类型

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 Rust 学习系列 ,rust中的原生类型 标量类型(scalar type) 布尔类型(bool):表示真假值。 字符类型(char):表示单个Unicode字符。 整数类型(integer):表示整数值,包括有符号和无符号整数。 有符号整

    2024年02月21日
    浏览(29)
  • 3.Rust数据类型

    Rust 每个值都有其确切的数据类型,总的来说可以分为两类:基本类型和复合类型。 Rust是一个强类型语言与js不同,我们在声明变量时就要指定该变量的类型,编译器必须在编译期知道我们所有变量的类型。当然大多时聪明的编译器可以自动推导类型,但为了保证代码质量和

    2024年03月10日
    浏览(51)
  • Rust 基础入门 —— 基本类型

    在Rust 中,作为强类型语言,自然会独立一块内容用作类型管理工作,而rust 中 为应用领域的扩展, 兼容了很多的数学计算方面的 内容,加到了基本类型中,例如 复数, 在有向图和 矢量图计算中的应用,rust 通过自带的类型设计避免了 程序员再开发的任务难度。 总的来说

    2024年02月12日
    浏览(30)
  • Rust之通用集合类型

    在Rust语言中包含了一系列被称为集合的数据结构。大部分的数据结构都代表着某个特定的值,但集合却可以包含多个值。与内置的数组与元组类型不同,这些集合将自己持有的数据存储在了堆上。这意味着数据的大小不需要在编译时确定,并且可以随着程序的运行按需扩大或

    2024年02月15日
    浏览(29)
  • Rust-类型

    布尔类型(bool)代表的是“是”和“否”的二值逻辑。它有两个值:true和false。 一般用在逻辑表达式中,可以执行“与”“或”“非”等运算。 字符类型由char表示。它可以描述任何一个符合unicode标准的字符值。在代码中,单个的字符字面量用单引号包围。 字符类型字面量也

    2024年01月16日
    浏览(41)
  • Rust类型之字符串

    Rust 中的字符串类型是 String 。虽然字符串只是比字符多了一个“串”字,但是在Rust中这两者的存储方式完全不一样,字符串不是字符的数组, String 内部存储的是 Unicode 字符串的 UTF8 编码,而 char 直接存的是 Unicode Scalar Value 。 Rust字符串对 Unicode 字符集有着良好的支持,可以

    2024年02月02日
    浏览(34)
  • 【Rust 基础篇】Rust Sized Trait:理解Sized Trait与动态大小类型

    Rust是一门以安全性和性能著称的系统级编程语言。在Rust中,类型大小的确定在编译期是非常重要的。然而,有些类型的大小在编译期是无法确定的,这就涉及到了Rust中的动态大小类型(DST)。为了保证在编译期可以确定类型的大小,Rust引入了Sized trait。本篇博客将深入探讨

    2024年02月14日
    浏览(30)
  • Rust语言精讲:数据类型全解析

    大家好!我是lincyang。 今天,我们将深入探讨Rust语言中的数据类型,这是理解和掌握Rust的基础。 Rust语言数据类型概览 Rust是静态类型语言,所有变量类型在编译时确定。Rust的数据类型分为两类:标量类型和复合类型。 标量类型 标量类型是单一值的类型,包括整型、浮点型

    2024年02月05日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包