Rust的数据类型

文章目录

Scalar Types

Integer

LengthSignedUnsigned
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
archisizeusize

signed: -$2^{n-1}$ to $2^{n-1}$-1

unsigned: 0 to $2^n$-1

PS. Integer Literals in Rust

Number literalsExample
Decimal98_222
Hex0xff
Octal0o77
Binary0b1111_0000
Byte (u8 only)b'A'

Floating-Point

f32: 单精度。

f64: 双精度,rust里小数默认是f64。

Boolean

使用 bool 声明布尔类型,包括 truefalse ,占一个 byte 大小。

Character

char 类型占四个 byte 大小。

Compound Types

Tuple

可以存放不同类型的数据,长度固定,一旦声明,将无法拓展或者压缩大小。

1
2
3
4
5
6
7
fn main() {
    let tup = (500, 6.4, 1);

    let (x, y, z) = tup;

    println!("The value of y is: {}", y);
}
1
2
3
4
5
6
7
8
9
fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);

    let five_hundred = x.0;

    let six_point_four = x.1;

    let one = x.2;
}

Array

里面的所有数据类型必须一致,长度和 Tuple 一样也是固定的,一旦声明将无法更改。

Array 里的数据存放在 stack 而不是 heap。

1
2
3
4
5
fn main() {
    let a = [1, 2, 3, 4, 5];
    let first = a[0];
    let second = a[1];
}
1
let a: [i32; 5] = [1, 2, 3, 4, 5];//i32是类型,5是长度
1
let a = [3; 5];//3是默认值,5是长度

评论正在加载中...如果评论较长时间无法加载,你可以 搜索对应的 issue 或者 新建一个 issue