Упражнения по Rust

Temperature Converter in Rust

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

  • Начальный
  • Чтение: 3 мин
  • Примеров для запуска: 1
Что вы узнаете
  • 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.

Главное

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

Пример на Rust, который можно запустить

Rust
Запустить код →
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)));
    }
}
Получить кнопку запуска для этого примера Результат выполнения
100.0°C = 212.0°F
98.6°F = 37.0°C
-40.0°C = -40.0°F

Практика

Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.

Закончили этот урок?

Отметьте его как изученный, чтобы следить за прогрессом.

Далее: Option: Values That May Be Missing →

Попрактикуйтесь на задаче

Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.

Все задачи