พื้นฐาน Rust
Rust Vectors: Vec<T>
A list that grows while the program runs: push, pop, sort and read items safely.
สิ่งที่คุณจะได้เรียนรู้
- vec! and push
- Indexing vs get
- sort and pop
vec![3, 1, 4] after two pushes
30
11
42
1push
5push
A growable list
A vector, written Vec<T>, is a list that can grow and shrink while the program runs. It is the collection you will use most often in Rust.
vec! creates a vector with starting values and push adds to the end. numbers[2] stops the program if the index does not exist, while get returns None instead. pop removes the last item and returns it inside Some.
ประเด็นสำคัญ
- push adds to the end, pop removes from the end.
numbers[10]stops the program if the index is missing.get(10)returns None instead.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
fn main() {
let mut numbers = vec![3, 1, 4];
numbers.push(1);
numbers.push(5);
println!("{:?}", numbers);
println!("length: {}", numbers.len());
println!("third: {}", numbers[2]);
match numbers.get(10) {
Some(value) => println!("found {value}"),
None => println!("no item at index 10"),
}
numbers.sort();
let last = numbers.pop();
println!("{:?} after pop, removed {:?}", numbers, last);
}
[3, 1, 4, 1, 5]
length: 5
third: 4
no item at index 10
[1, 1, 3, 4] after pop, removed Some(5)ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- หาผลรวมของอาเรย์ หาผลรวมของค่าทั้งหมดในลิสต์ ง่าย
- ค่าเฉลี่ยของอาเรย์ คำนวณค่าเฉลี่ยของรายการตัวเลข ง่าย