字面量

数字字面量可以通过添加类型后缀来指定类型。例如,要指定字面量 42 的类型为 i32,可以写作 42i32

未添加后缀的数字字面量的类型将取决于它们的使用方式。如果不存在约束,编译器将使用 i32 作为整数类型,使用 f64 作为浮点数类型。

fn main() {
    // Suffixed literals, their types are known at initialization
    let x = 1u8;
    let y = 2u32;
    let z = 3f32;

    // Unsuffixed literals, their types depend on how they are used
    let i = 1;
    let f = 1.0;

    // `size_of_val` returns the size of a variable in bytes
    println!("size of `x` in bytes: {}", std::mem::size_of_val(&x));
    println!("size of `y` in bytes: {}", std::mem::size_of_val(&y));
    println!("size of `z` in bytes: {}", std::mem::size_of_val(&z));
    println!("size of `i` in bytes: {}", std::mem::size_of_val(&i));
    println!("size of `f` in bytes: {}", std::mem::size_of_val(&f));
}

之前的代码中使用了一些尚未解释的概念,这里为心急的读者做一个简短的解释:

  • std::mem::size_of_val 是一个函数,但它使用完整路径调用。代码可以拆分为称为模块的逻辑单元。 在这种情况下,size_of_val 函数定义在 mem 模块中,而 mem 模块定义在 std crate 中。 更多细节,请参阅 模块crate