Rust- 类型转换

2023-11-19

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.

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rust- 类型转换 的相关文章

随机推荐

  • 【日记】转行驱动

    从今天开始换到驱动组了 完成手头上的应用任务就彻底挥别应用 Unity再见
  • apache httpclient 连接池 工具_HttpClient连接池的一些思考

    前言 使用apache的httpclient进行http的交互处理已经很长时间了 而httpclient实例则使用了http连接池 想必大家也没有关心过连接池的管理 事实上 通过分析httpclient源码 发现它很优雅地隐藏了所有的连接池
  • 汇编语言mov al,0c5h,用汇编语言编程

    匿名用户 1级 2008 10 30 回答 写一下简单的算法吧 先提供一个简单的画点子程序 在屏幕显示一点或一像素子程序 输入参数 BX 行地址 0 479 SI 列地址 0 639 DL 颜色 0 15 640 480显示模式 DOT p
  • unity数学函数mathf.PinPong的实现原理

    mathf这个库十分强大 基本上封装了 游戏数学方面的函数 先介绍一个Mathf pingpong 官方api Mathf PingPong 乒乓 static function PingPong t float length float
  • 《高效能程序员的修炼》目录及部分精彩章节

    高效能程序员的修炼 本书已上市 各大书店均有销售 谢谢支持 目 录 1 入门须知 1 1 你想当一个程序员 1 2 程序员的八种境界 1 3 如何培养写作习惯 2 把一堆烂事搞定的艺术 2 1 学海无边 2 2 磨刀不误砍柴工 2 3 一路
  • 深入探索透视纹理映射(下)

    在上一篇文章中 我们探讨了学习透视纹理映射所需要的基础知识 我们知道了顶点在通过透视投影变换之后 是如何一步一步通过流水线进入屏幕空间的 也知道了一个非常简单的三角形扫描线转换算法 以及通过线性插值实现的仿射纹理映射 尽管我们使用的这个流程
  • 图片自动填充单元格_Excel合并单元格后进行快编号填充,你还为这个操作苦恼吗?...

    我们在工作中常常会遇到这样的情况 经常需要对某些行进行合并 但是 这个时候可能就会遇到一个问题 合并了行以后如何进行自动序号填充呢 使用Excel自带的向下拉填充序列的方式是不能正确填充的 今天 给大家介绍一种能够对合并单元格进行序号填充的
  • Clion中单行注释、多行注释及取消注释快捷键示例

    添加注释 单行注释 光标定位到指定代码行 Ctrl 多行注释 光标选定多行代码 Ctrl shift 取消注释 取消注释与添加注释快捷键相同 单行注释 光标定位到指定代码行 Ctrl 多行注释 光标定位到多行注释中 或选定全部被注释的内容
  • feignclient发送get请求,传递参数为对象。

    feignclient发送get请求 传递参数为对象 此时不能使用在地址栏传递参数的方式 需要将参数放到请求体中 第一步 修改application yml中配置feign发送请求使用apache httpclient 而不是默认的jdk
  • 做什么副业比较赚钱,这五个项目现在入行可能比上班挣得还多

    还有2个月不到的时间 2022就要过去了 这一年太魔幻了 而普通人的生活也的确太难了 这一年 各行各业都在萎缩 制造业急剧萎缩 要么不能静态生产 要么生产了就送不出去 因为可能是疫区 也可能是收货地 这样老板和员工都赚不到钱 中小商户和商铺
  • 我们无法设置移动热点_Win10 校园拨号连接情况下开热点

    win10校园网下开启热点 本段文字用以解决win10下无法建立移动热点 错误提示为 我们无法设置移动热点 因为你的电脑未建立以太网 WIFI或手机网络连接 这个问题可能出现在拨号上网连接的设备上 这也就是说我们的电脑现在无法识别出我们所用
  • java 读取resource下的文件

    目录 一 普通main代码里使用 1 假设有如下结构的代码 1 main方法里复制resource下的文件 2 main方法里读取resource下的文件 2 假设有如下结构的代码 二 对于springboot项目读取resource下的资
  • JDBC数据源连接池(4)---自定义数据源连接池

    JDBC数据源连接池 4 自定义数据源连接池 续上文 JDBC数据源连接池 3 Tomcat集成DBCP 我们已经 了解了DBCP C3P0 以及Tomcat内置的数据源连接池 那么 这些数据源连接池是如何实现的呢 为了究其原理 我在这里写
  • Bootstarp入门教程(5) 排版(2)

    3 缩略语 当鼠标悬停在缩写和缩写词上时就会显示完整内容 Bootstrap实现了对HTML的
  • 如何理解和解决高并发

    如何理解高并发 高并发指的两方面 提升硬件 负载均衡 使用缓存 缓存一致性如何保证 限流 DNS负载均衡 线程池和分布式锁 总结 高并发指的两方面 同一时刻有大量的请求访问系统 有大量的请求并行访问系统 当大量请求短时间内涌入系统的时候 我
  • 2018中国汽车企业排行榜TOP10

    看排名 懂中国汽车 Aming 汽车行业变化很快 但是从上市车企的情况来看 可以看到具体的财报数字 因而可以知道一个更具体的发展情况 不过这次的排行榜主要针对2018年上半年中国已经上市的汽车企业 特别推出利润排行榜与销量排行榜 同时还有利
  • Dockerfile讲解和案例分享

    目录 dockerfile是在容器外部 构建三部曲 dockerfile基本知识 dockerfile执行流程 dockerfile 常用保留字 FROM MAINTAINER RUN EXPOSE WORKDIR USER ENV ADD
  • 40个学术网站

    40个学术网站 满足你的科研需求 2018 03 06 美国留学那点事 文 中外学术情报 微信号 Academic Information 科研工作者每天日常莫过于看文献 做实验 写论文 人生最郁闷的事情不过于是导师说 那个XX 帮我下载下
  • java secretkey用法_Java SecretKeyFactory.generateSecret方法代码示例

    本文整理汇总了Java中javax crypto SecretKeyFactory generateSecret方法的典型用法代码示例 如果您正苦于以下问题 Java SecretKeyFactory generateSecret方法的具体
  • Rust- 类型转换

    Rust is a statically typed language which means that it emphasizes on knowing the types of all variables at compile time