Menu
Coddy logo textTech

From과 Into

Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 57번째.

Rust에서 타입 간 변환은 흔히 수행하는 작업입니다. From 트레이트는 한 타입을 다른 타입으로부터 생성하는 방법을 정의하는 표준화된 방식을 제공합니다. From을 구현하면 Into 트레이트를 automatically free로 얻을 수 있습니다.

From을 구현하려면 다른 타입에서 자신의 타입을 생성하는 방법을 정의합니다:

struct Meters(f64);
struct Kilometers(f64);

impl From<Kilometers> for Meters {
    fn from(km: Kilometers) -> Self {
        Meters(km.0 * 1000.0)
    }
}

이제 from 함수 또는 into 메서드를 사용하여 변환할 수 있습니다:

let distance = Kilometers(5.0);

// From을 명시적으로 사용
let m1 = Meters::from(distance);

// Into 사용 (From이 구현되어 있기 때문에 작동함)
let distance = Kilometers(3.0);
let m2: Meters = distance.into();

into() 메서드는 Rust가 어떤 타입으로 변환하는지 알아야 하므로 타입 annotation이 필요합니다. 이 패턴은 구성 데이터를 초기화된 객체로 변환하거나 원시 input을 검증된 구조체로 변환하는 것처럼, helper 구조체를 주요 타입으로 변환해야 하는 경우에 특히 유용합니다.

challenge icon

챌린지

쉬움

From 트레이트를 사용하여 온도 변환 시스템을 만들어 봅시다! 두 가지 온도 타입인 CelsiusFahrenheit를 만들고, Rust의 표준 변환 트레이트를 사용하여 두 타입 간의 변환을 implementing합니다.

코드를 두 파일에 걸쳐 구성합니다:

  • temperature.rs: 두 개의 public newtype struct인 CelsiusFahrenheit를 Define합니다. 두 struct 모두 f64를 감쌉니다. 다음 formula를 사용하여 CelsiusFahrenheit로 변환하도록 From 트레이트를 Implement합니다: fahrenheit = celsius × 1.8 + 32.0. 또한 각 struct에 내부 f64를 returns하는 value method를 추가합니다.
  • main.rs: temperature 모듈을 가져오고 두 가지 변환 방법을 보여 줍니다. 제공된 input으로부터 Celsius 값을 Create한 다음, Fahrenheit::from()을 사용하여 Fahrenheit로 변환합니다. another Celsius 값을 Create하고 .into() method를 사용하여 변환합니다. 두 results를 Print합니다.

Celsius에서 Fahrenheit로의 변환 formula는 1.8을 곱한 다음 32를 더하는 것입니다. Remember: From<Celsius> for Fahrenheit를 implementing하면 CelsiusInto<Fahrenheit> 트레이트가 automatically 제공되므로 free입니다!

두 온도는 모두 정수로 출력됩니다. 각 f64as i64로 변환하면 소수 부분이 0을 향해 잘립니다. 따라서 input 36.636C로 출력되고, 이 값이 변환되는 97.88 Fahrenheit는 97F로 출력됩니다. 반올림되지 않습니다.

출력은 다음 format으로 두 변환 결과를 표시해야 합니다:

From: {celsius1}C = {fahrenheit1}F
Into: {celsius2}C = {fahrenheit2}F

예를 들어 input이 0100인 경우:

From: 0C = 32F
Into: 100C = 212F

그리고 input이 25-40인 경우:

From: 25C = 77F
Into: -40C = -40F

두 개의 input을 받습니다. 첫 번째 Celsius 값은 f64로 parse하고, 두 번째 Celsius 값도 f64로 parse합니다.

직접 해보기

mod temperature;

use temperature::{Celsius, Fahrenheit};

fn main() {
    // 입력 읽기
    let mut input1 = String::new();
    std::io::stdin().read_line(&mut input1).expect("Failed to read line");
    let celsius1: f64 = input1.trim().parse().expect("Invalid number");
    
    let mut input2 = String::new();
    std::io::stdin().read_line(&mut input2).expect("Failed to read line");
    let celsius2: f64 = input2.trim().parse().expect("Invalid number");
    
    // TODO: celsius1에서 Celsius 값 생성
    // TODO: Fahrenheit::from()을 사용하여 Fahrenheit로 변환
    
    // TODO: celsius2에서 또 다른 Celsius 값 생성
    // TODO: .into()을 사용하여 Fahrenheit로 변환
    
    // TODO: 다음 형식으로 결과 출력:
    // From: {celsius1}C = {fahrenheit1}F
    // Into: {celsius2}C = {fahrenheit2}F
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Rust 컴파일러