Struct, Enum และ Trait

Rust Generics

Write a function or struct once and use it with many types, with no cost at run time.

  • ระดับกลาง
  • อ่าน 3 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • Type parameters
  • Trait bounds
  • Generic structs
largest<T>
largest(&[3, 9, 4])9
largest(&[2.5, 1.5])2.5
largest(&['x', 'b'])'x'

One definition, many types

Generics let you write code once and use it with different types. A type parameter such as T stands for a type that is chosen where the code is used.

T: PartialOrd + Copy is a trait bound: largest accepts any type that can be compared and copied, so it works with integers, floats and characters. Pair<T> is a generic struct, and its impl block is generic too. The compiler creates a separate version for each type, so generics cost nothing at run time.

ประเด็นสำคัญ

  1. T stands for a type chosen at the call.
  2. T: PartialOrd limits T to comparable types.
  3. The compiler makes a version per type.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
    let mut largest = items[0];
    for &item in items {
        if item > largest {
            largest = item;
        }
    }
    largest
}

#[derive(Debug)]
struct Pair<T> {
    left: T,
    right: T,
}

impl<T: Copy> Pair<T> {
    fn swap(&self) -> Pair<T> {
        Pair { left: self.right, right: self.left }
    }
}

fn main() {
    println!("{}", largest(&[3, 9, 4]));
    println!("{}", largest(&[2.5, 1.5]));
    println!("{}", largest(&['x', 'b']));

    let pair = Pair { left: "a", right: "b" };
    println!("{:?}", pair.swap());
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
9
2.5
x
Pair { left: "b", right: "a" }

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด