Rust- 类型系统

chatgpt/2023/9/24 2:04:49

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.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.exyb.cn/news/show-5314377.html

如若内容造成侵权/违法违规/事实不符,请联系郑州代理记账网进行投诉反馈,一经查实,立即删除!

相关文章

msvcp140.dll丢失怎么修复?《绝地求生》报错msvcp140.dll丢失修复方法

在我运行《绝地求生》游戏的时候&#xff0c;出现msvcp140.dll丢失的错误提示时&#xff0c;感到有些困扰和不安&#xff0c;不知道该如何解决这个问题。同时&#xff0c;我也会担心这个问题会对我使用电脑产生什么不利影响。在尝试解决这个问题之前&#xff0c;我开始意识到我…

day56|● 583. 两个字符串的删除操作 ● 72. 编辑距离

● 583. 两个字符串的删除操作 Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. can delete in either string. Input: word1 “sea”, word2 “eat” Output: 2 Explanation: You need one step to mak…

设计原则学习之里氏替换原则

以下内容均来自抖音号【it楠老师教java】的设计模式课程。 1、原理概述 子类对象&#xff08;objectofsubtype/derivedclass&#xff09;能够替换程序&#xff08;program&#xff09;中父类对象&#xff08;objectofbase/parentclass&#xff09;出现的任何地方&#xff0c…

手写MyBatis代码生成器Maven插件

代码链接&#xff1a;codegen-maven-plugin 在使用MyBatis时&#xff0c;需要根据库表结构编写一些通用的Mapper interface、XML、Entity&#xff0c;这些重复操作可以通过代码生成器自动生成&#xff0c;大大提高开发效率。 目前&#xff0c;代码生成分为两种方式&#xff1a…

【flutter】flutter如何让app内字体大小不随着系统改变而改变

如果我们不特意设置&#xff0c;flutter开发的app他的字体大小是会跟着系统设置的字体大小而改变&#xff0c;这样就会导致页面出现布局错乱问题&#xff0c;那么如何解决这个问题呢&#xff1f;我也搜索了相关资料&#xff0c;有两个常用也是网络上搜集到比较多的方法&#xf…

中国计算机学会推荐国际学术期刊(网络与信息安全)

序号刊物简称刊物全称分类类型专业领域1TDSCIEEE Transactions on Dependable and Secure ComputingA期刊网络与信息安全2TIFSIEEE Transactions on Information Forensics and SecurityA期刊网络与信息安全3Journal of CryptologyA期刊网络与信息安全1TISSECACM Transactions …

通过SSH实现将本地端口反向代理到公网服务器

使用场景 有一台公网服务器&#xff0c;能够对外开放服务进行访问&#xff0c;但是这个公网服务器资源较低&#xff0c;无法运行太多服务 有一台闲置电脑可以全天候开机使用&#xff0c;且配置较好&#xff0c;可以部署多个服务&#xff0c;但是没有公网IP 需求&#xff1a;将…

时序预测 | Python实现NARX-DNN空气质量预测

时序预测 | Python实现NARX-DNN空气质量预测 目录 时序预测 | Python实现NARX-DNN空气质量预测效果一览基本介绍研究内容程序设计参考资料效果一览 基本介绍 时序预测 | Python实现NARX-DNN空气质量预测 研究内容 Python实现NARX-DNN空气质量预测,使用深度神经网络对比利时空气…
推荐文章