Primitives(基本数据类型)

Rust提供了几种数据类型

  • 整数类型: i8, i16, i32, i64, i128 和isize(指针)
  • 无符号整数类型: u8, u16, u32, u64, u128 和usize(指针)
  • 浮点: f32, f64
  • char类型(4个比特)
  • bool类型
  • 元祖类型()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fn main() {
    // Variables can be type annotated.
    let logical: bool = true;

    let a_float: f64 = 1.0;  // Regular annotation
    let an_integer   = 5i32; // Suffix annotation

    // Or a default will be used.
    let default_float   = 3.0; // `f64`
    let default_integer = 7;   // `i32`
    
    // A type can also be inferred from context 
    let mut inferred_type = 12; // Type i64 is inferred from another line
    inferred_type = 4294967296i64;
    
    // A mutable variable's value can be changed.
    let mut mutable = 12; // Mutable `i32`
    mutable = 21;
    
    // Error! The type of a variable can't be changed.
    mutable = true;
    
    // Variables can be overwritten with shadowing.
    let mutable = true;
}

注意

1_0001000是一样的,为什么有这个奇怪的规定,(便于阅读?)

1
2
let a: i32 = 1000;
let c: f64 = 0.000_001;

例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fn main() {
    println!("1 + 2 = {}", 1u32 + 2);
    println!("1 - 2 = {}", 1i32 - 2);
    println!("true AND false is {}", true && false);
    println!("true OR false is {}", true || false);
    println!("NOT true is {}", !true);

    println!("0011 AND 0101 is {:04b}", 0b0011u32 & 0b0101);
    println!("0011 OR 0101 is {:04b}", 0b0011u32 | 0b0101);
    println!("0011 XOR 0101 is {:04b}", 0b0011u32 ^ 0b0101);
    println!("1 << 5 is {}", 1u32 << 5);
    println!("0x80 >> 2 is 0x{:x}", 0x80u32 >> 2);

    println!("One million is written as {}", 1_000_000u32);
}

元祖

rust中的元祖和其他语言的功能基本一样,都是可以拥有不同的类型。

1
2
let tuple = (1, "hello", 4.5, true);
let (a, b, c, d) = tuple;

数组

1
2
3
4
let xs: [i32; 5] = [1, 2, 3, 4, 5];
println!("array occupies {} bytes", mem::size_of_val(&xs));
let ys = &xs[1..4]; //切片
println!("{}",ys[0]); //2

参考