rust所有变量默认是不可变

声明增加 mut 才可以改变

rust 数据类型

rust是静态类型语言

Scalar Types

  • integer

    LengthSignedUnsigned
    8i8u8
    16i16u16
    32i32u32
    64i64u64
    128i128u128
    archisizeusize

    iszieusize取决于电脑架构 int 默认是i32

    声明示例

    literals示例
    Decimal1_000
    Hex0xff
    Octal0o77
    Binary0b1111_0000
    Byte(u8 only)b'A'

    标准库中处理溢出的方法

    • wrapping_* 循环
    • checked_* 溢出返回None
    • overflowing_* 返回数字值和是否溢出
    • saturating_* 返回最接近的值
  • floating-point

    • f32
    • f64 默认 let x = 2.0 //f64
  • boolean 1 byte长度 使用 bool

  • character 4 byte长度 使用 char

    #![allow(unused)]
    fn main() {
    let z: char = 'ℤ'; // with explicit type annotation
    let heart_eyed_cat = '😻';
    }

Compound Types

  • tuple 固定长度,声明后长度不能变动 两种使用方式 1 destructuring

      fn main() {
        let tup = (500, 6.4, 1);
    
        let (x, y, z) = tup;
    
        println!("The value of y is: {y}");
    } 

    2 indexing

      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;
    }

    空元组 ()unit,表示一个空值或者一个空的返回类型,表达式在返回空值时隐式返回 unit

  • array 固定长度,分配在栈上

    #![allow(unused)]
    fn main() {
    let months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];
    }

    声明时指定类型和长度

    #![allow(unused)]
    fn main() {
     let a: [i32; 5] = [1, 2, 3, 4, 5];
    }

    指定相同内容和长度

    #![allow(unused)]
    fn main() {
    let a = [3; 5]; //a = [3, 3, 3, 3, 3]
    }