Bài tập Rust

Temperature Converter in Rust

Convert between Celsius and Fahrenheit with an enum that remembers the unit.

  • Cơ bản
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • An enum with data
  • match to convert
  • Formatting with {:.1}
convert
100.0°C212.0°F
98.6°F37.0°C
-40.0°C-40.0°F

The unit is part of the value

An enum can record which unit a temperature uses, so the compiler stops you from mixing Celsius and Fahrenheit by accident.

convert matches on the variant and returns the other one. show formats the number with one digit after the decimal point. -40 is the one temperature that is the same on both scales.

Những điểm quan trọng

  1. Each variant carries the number.
  2. match returns the other unit.
  3. -40 is the same on both scales.

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

Rust
Chạy code →
main.rs
enum Temperature {
    Celsius(f64),
    Fahrenheit(f64),
}

fn convert(temperature: &Temperature) -> Temperature {
    match temperature {
        Temperature::Celsius(c) => Temperature::Fahrenheit(c * 9.0 / 5.0 + 32.0),
        Temperature::Fahrenheit(f) => Temperature::Celsius((f - 32.0) * 5.0 / 9.0),
    }
}

fn show(temperature: &Temperature) -> String {
    match temperature {
        Temperature::Celsius(c) => format!("{c:.1}°C"),
        Temperature::Fahrenheit(f) => format!("{f:.1}°F"),
    }
}

fn main() {
    for input in [Temperature::Celsius(100.0), Temperature::Fahrenheit(98.6), Temperature::Celsius(-40.0)] {
        println!("{} = {}", show(&input), show(&convert(&input)));
    }
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
100.0°C = 212.0°F
98.6°F = 37.0°C
-40.0°C = -40.0°F

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