Rust- 类型系统

2023-11-16

The type system in Rust is one of its core features, supporting a range of different types and providing a powerful system for static type checking.

In Rust, the type of all variables is determined at compile time. This means that if you try to use a value as a different type at runtime, Rust’s compiler will throw an error at the compile stage, not at runtime.

Here are some of the main types in Rust:

  1. Primitive Types: These include integer types (like i32, u32), floating-point types (f32, f64), boolean (bool), and character (char).

  2. Compound Types: These include tuples and arrays. Tuples are a collection of values of different types, while arrays are a collection of values of the same type.

  3. String Types: Rust has two main string types, String and str. String is a growable, heap-allocated string type, while str typically exists as a slice (which represents a fixed-size string).

  4. Smart Pointer Types: Such as Box<T>, Rc<T>, and RefCell<T>. These types provide advanced features for memory safety and management.

  5. Custom Types: You can define your own types using the struct keyword or define an enumeration type using the enum keyword.

  6. Function Types: Functions are also a type that can be passed as parameters or returned from other functions.

  7. Trait Types: Rust uses traits to define shared behavior across multiple types. They’re similar to interfaces in other languages (like Java interfaces).

  8. Option and Result Types: These two types are fundamental to how Rust handles nullability and error handling.

The above is an overview of the Rust type system, but there’s much more depth and detail. Rust’s type system makes it an incredibly powerful and safe language, catching many type errors at compile time, and preventing many common runtime errors.

fn main() {
    let spend = 1;
    // 错误!不提供隐式转换
    // let cost: f64 = spend;  // mismatched types expected `f64`, found integer

    // 可以显式转换
    let cost = spend as f64;
    println!("转换 {} -> {}", spend, cost);     // 转换 1 -> 1

    // 带后缀的字面量,其类型在初始化时已经知道了
    let x = 1u8;
    let y = 2u32;
    let z = 3f32;

    // 无后缀的字面量,编译器有默认类型
    let i = 1;
    let f = 1.0;

    let study = String::from("Rust");

    let mut vec = Vec::new();
    vec.push(study);
    println!("{:?}", vec);                      // ["Rust"]

    // 别名  要用驼峰命名法CamelCase
    // 别名不是新类型,不提供额外的类型安全

    let myU64:MyU64 = 5 as ThirdU64;
    let otherU64:OtherU64 = 2 as ThirdU64;
    println!("{} MyU64 + {} OtherU64 = {}", myU64, otherU64, myU64 + otherU64); // 5 MyU64 + 2 OtherU64 = 7

}

type MyU64 = u64;
type OtherU64 = u64;
type ThirdU64 = u64;

It is worth noting that in Rust, functions are also treated as a type and can be assigned to variables, passed as function parameters, and returned from other functions. This supports the concept of first-class functions and higher-order functions in the language.

Here’s a simple example:

fn main() {
    let greeter: fn(&str) -> String = create_greeting;
    println!("{}", greeter("World"));
}

fn create_greeting(name: &str) -> String {
    format!("Hello, {}!", name)
}

In this example, greeter is a variable of a function type. It is assigned to the function create_greeting, which takes a reference to a string and returns a new String. Later on, greeter can be used just like a regular function.

You can also use function types to define higher-order functions, i.e., functions that take functions as parameters or return functions as results. Here’s an example of a higher-order function:

fn main() {
    let result = apply_twice(add_three, 7);
    println!("{}", result);  // 13
}

fn apply_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
    f(f(arg))
}

fn add_three(x: i32) -> i32 {
    x + 3
}

In this example, apply_twice is a higher-order function. It takes a function f and an argument arg, applies f to arg twice, and returns the result.

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

Rust- 类型系统 的相关文章

随机推荐

  • sqli-labs(24)

    这个关卡可能有时候会出现一些小问题 有时候登陆后是没有修改密码的选项的 这是因为有时候解压时logged in php文件解压不正确 重新解压即可 本关卡为二次注入 其产生原因是 服务器端虽然对用户的直接输入做了一些过滤或者将一些字符进行转
  • 数字经济专家高泽龙谈“金融元宇宙”与“元宇宙金融”

    开始聊所有话题之前 必须先说说 金融元宇宙 或者 元宇宙金融 的概念和定义 当然 前提是搞清楚 金融 和 元宇宙 百度百科中 金融 的定义 金融 Finance Finaunce 是市场主体利用金融工具将资金从资金盈余方流向资金稀缺方的经济
  • Python读取文件时出现UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position xx: 解决方案

    Python在读取文件时 with open article txt as f 打开新的文本 text new f read 读取文本数据 出现错误 UnicodeDecodeError gbk codec can t decode byt
  • electron autoUpdater热更新

    最近创建了一个electron vue项目 用到了热更新 先看效果图 话不多说 直接上代码 main目录下创建update js 代码如下 安装包helatest yml所在服务器地址 const uploadUrl http 127 0
  • 金山WPS暑期实习招聘笔试题2013-7-28

    C 试卷B卷 应聘职位1 2 姓 名 性 别 学 位 所在院校 所学专业 联系电话 电子邮件 毕业时间 获知招聘信息渠道 说明 答题时间为 100 分钟 自我判断题 请选择最符合您本人意愿的一项 1 你
  • 从项目实施层面解析STEAM教育

    转自 https baijiahao baidu com s id 1614434815561381532 wfr spider for pc 一 引言 近几年大家常常听到STEAM教育这个词 似乎一夜之间所有的培训机构的课程都变成了STE
  • 第9章_瑞萨MCU零基础入门系列教程之SCI I2C

    本教程基于韦东山百问网出的 DShanMCU RA6M5开发板 进行编写 需要的同学可以在这里获取 https item taobao com item htm id 728461040949 配套资料获取 https renesas do
  • Android-SharedPreferences实现记住密码和自动登录

    效果图 第一次进入进来 勾选记住密码和自动登录成功后 第二次进来 说明 中间存在的图片或者多余的其他部分可删掉 留下最主要的填写部分和登陆按钮即可 功能还是可以实现的 XML文件
  • QQ飞车手游设计分析

    腾讯系竞速手游的逆袭 QQ飞车手游设计分析 前言 这是中山大学数据科学与计算机学院软件工程2019年3D游戏编程与设计的作业1 导语 在中国巨大的游戏市场下 手游战场上的战火从未熄灭 其中以王者荣耀为首的MOBA类手游与以PUBG 现改名和
  • 【Flink Rest-ful API 】

    Flink 有了一些查询job状态指标的API 这些监控 API is a REST ful API 接受 HTTP 请求并返回JSON data 这些监控API以jobManager中web server 为基础 默认其监听端口为8081
  • PHPstudy安装教程

    首先简单介绍一下PHPStudy PHPStudy是一个Windows下的Apache Nginx php MYSQL的集成开发环境 PHPStudy比较适合快速的在windows下部署一个Web开发环境 而且便于安装 部署方便 服务器本身
  • linux环境下安装nginx

    一 准备安装环境 安装nginx需要系统相关插件 所以在安装前先检查哈是否有这些插件 如果没有 则要先安装这些插件 由于笔者是新的虚拟机环境 所以这些插件都没有 都需要安装 读者可以根据自己实际情况进行相关操作 1 安装 gcc gcc c
  • HTML引用公共组件

    在test html引用footer html 效果图 代码 test html div 我是頁面 div div class footer div
  • 《再也不怕elasticsearch》REST API调用

    REST API调用 大家好我是迷途 一个在互联网行业 摸爬滚打的学子 热爱学习 热爱代码 热爱技术 热爱互联网的一切 再也不怕elasticsearch系列 帅途会慢慢由浅入深 为大家剖析一遍 各位大佬请放心 虽然这个系列帅途有时候更新的
  • linux桌面小程序开发日记2(pyqt5+yolov5)

    linux桌面小程序开发日记2 使用Pyqt5 制作一个界面 并连接摄像头 最后一篇博客地址 https blog csdn net Liuchengzhizhi article details 123692365 B站视频 https w
  • VS Code Material Icon Theme插件设置自定义文件夹图标关联

    VS Code Material Icon Theme插件设置自定义文件夹图标关联 方法与分析 自定义文件夹图片命名和位置如下 vscode extensions pkief material icon theme 4 5 0 icons
  • 程序的基本结构

    程序的基本结构 1 顺序结构 2 选择结构 选择结构如下图所示 当条件成立时 执行模块A否则执行模块B 3 循环结构 循环结构又两种形式当型循环和直道型循环 当型循环 先判断条件 条件成立就反复执行程序模块 当条件不成立时结束循环 当型循环
  • Django视图类View源码分析

    Django视图类View源码分析 一 视图函数 django中的视图函数 就是视图功能由函数实现 响应 或渲染模板后返回HTML 或直接返回JSON数据 参数 视图函数的第一个参数必须是request对象 文本响应 from django
  • 纯干货:接口自动化测试的思考和技术实现

    一 思考 什么是自动化测试 自动化测试是把人为驱动转换成计算机驱的测试行为 人对于接口的测试行为 第一步 理解业务需求 一般来说可以从需求理解接口的行为和描述 行为 当什么情况 做什么操作 发生什么事情 描述 情况是什么 操作是什么等 第二
  • Rust- 类型系统

    The type system in Rust is one of its core features supporting a range of different types and providing a powerful syste