Struct, enum và trait

Rust Generics

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

  • Trung cấp
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

  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.

Ví dụ Rust chạy được

Rust
Chạy code →
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());
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
9
2.5
x
Pair { left: "b", right: "a" }

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách