通过例子学习Rust

5.2 字面常量

数值字面常量(Numeric literals)后面加上类型名称作为后缀,可用作声明它的类型。有两个例外,uint类型使用u后缀、int类型使用i后缀。

未添加类型后缀的字面常量,其类型依赖于后续如何使用。如果编译器不能确定,将会报错。

fn main() { // Suffixed literals, their types are known at initialization let x = 1u8; let y = 2u; let z = 3f32; // Unsuffixed literal, 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)); // Constraints (summands must have the same type) for `i` and `f` let _constraint_i = x + i; let _constraint_f = z + f; // TODO ^ Try commenting out these two lines }

上述代码中出现一些新概念,简要介绍如下:

  • fun(&foo) 向函数传递参数的 引用 而不是 (fun(foo)). 详情请看 借用
  • std::mem::size_of_val 带有全路径(full path)的函数。代码可按逻辑分割为不同的模块(Modules),函数 size_of_val 被定义在模块 mem 内,而模块 mem 被定义在库(Libraries,Rust术语叫Crate) std 内。详情可见 modulescrates