标量类型与复合类型
你会学到什么
- scalar type(标量类型)表示单个值。
- compound type(复合类型)把多个值组合在一起。
- array 长度是类型的一部分。
最小示例
let version: u32 = 2024;
let ratio: f64 = 0.85;
let passed: bool = true;
let symbol: char = 'R';
let point: (i32, i32) = (3, 5);
let scores: [u32; 3] = [80, 90, 100];
运行代码
cd examples
cargo run -p rt_03_scalar_compound_types
cargo test -p rt_03_scalar_compound_types
代码讲解
整数类型可以有符号,也可以无符号,例如 i32 和 u32。浮点类型常用 f64。
tuple 可以组合不同类型,array 要求元素类型一致且长度固定:
let profile = ("Rust", 2024, true);
let levels = ["beginner", "intermediate", "advanced"];
常见错误
array 的长度不同就是不同类型:
let a: [u8; 3] = [1, 2, 3];
let b: [u8; 4] = [1, 2, 3, 4];
a 和 b 不能直接赋给同一个固定类型变量。
练习
- 新增一个 tuple 表示章节标题和预计分钟数。
- 新增一个 array 存储三个标签。
小结
基础类型决定了值能做什么操作,也决定了函数签名如何表达约束。
下一步
下一章学习函数、参数和返回值。
完整示例代码
下面是 examples/03_scalar_compound_types/ 的完整源码。无需 clone 仓库,直接在页面上阅读、复制、对照运行。
examples/03_scalar_compound_types/src/main.rs
fn temperature_report(celsius: f64) -> (f64, bool) {
let fahrenheit = celsius * 9.0 / 5.0 + 32.0;
let is_hot = celsius >= 30.0;
(fahrenheit, is_hot)
}
fn first_and_last(values: [i32; 4]) -> (i32, i32) {
(values[0], values[values.len() - 1])
}
fn main() {
let celsius = 30.0;
let (fahrenheit, is_hot) = temperature_report(celsius);
let (first, last) = first_and_last([10, 20, 30, 40]);
println!("{celsius:.0}°C = {fahrenheit:.0}°F, hot: {is_hot}");
println!("first = {first}, last = {last}");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_temperature() {
let (fahrenheit, is_hot) = temperature_report(30.0);
assert!((fahrenheit - 86.0).abs() < f64::EPSILON);
assert!(is_hot);
}
#[test]
fn reads_array_edges() {
assert_eq!(first_and_last([1, 2, 3, 4]), (1, 4));
}
} examples/03_scalar_compound_types/Cargo.toml
[package]
name = "rt_03_scalar_compound_types"
version.workspace = true
edition.workspace = true
publish.workspace = true