Rust 基本类型

基本类型

像其他语言一样,Rust同样在标准库中內建了许多基本类型。

bool

let x = true;

let y: bool = false;

char

let x = 'x';
let two_hearts = '��';

数值类型

Rust提供多种数值类型,如下:

i8

i16

i32

i64

u8

u16

u32

u64

isize

usize

f32

f64

Rust中,整数类型分类有符号数和无符号数。例如 4位的有符号数可以表示 -8 ~ 7,无符号数可以表示 0 ~ 15.

Arrays

Rust中 数组必须是同一类型,默认,数组是不可变的!

let a = [1, 2, 3]; // a: [i32; 3]
let mut m = [1, 2, 3]; // m: [i32; 3]
let a = [0; 20]; // a: [i32; 20]

上面代码会生成一个 长度为20,初始化为0 的数组。

获取数组的长度可以使用len()函数

let a = [1, 2, 3];

println!("a has {} elements", a.len());

Slices

后来诞生的语言总视乎都有切片这个概念,比如python、golang。Rust中同样也有!

在Rust中,切片不能被直接创建。切片表现为指向数据开始的指针!所以使用切片,不会copy数组。

let a = [0, 1, 2, 3, 4];
let complete = &a[..]; // A slice containing all of the elements in a
let middle = &a[1..4]; // A slice of a: only the elements 1, 2, and 3

str

str 是最基本的字符串类型,是无长度类型,并不是特别有用。 官方文档中称 str 为字符串的切片。并给出下面的列子。

let hello = "Hello, world!";

// with an explicit type annotation
let hello: &'static str = "Hello, world!";

tuples

tuple 是长度固定的有序列表。

let x = (1, "hello");
let x: (i32, &str) = (1, "hello");

由上面的代码可以看出,tuple 可以存储不同的类型的变量。

let mut x = (1, 2); // x: (i32, i32)
let y = (2, 3); // y: (i32, i32)

x = y;

如果 tuple的类型 和参数是相同的,其引用可以指向另一个tuple

访问tuple元素:

let tuple = (1, 2, 3);

let x = tuple.0;
let y = tuple.1;
let z = tuple.2;

println!("x is {}", x);