Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

String 변환

문자열로 변환하기

어떤 타입을 String으로 변환하는 것은 해당 타입에 대해 ToString 트레이트를 구현하는 것만큼 간단합니다. 직접 구현하기보다는 fmt::Display 트레이트를 구현하는 것이 좋습니다. 이는 자동으로 ToString을 제공할 뿐만 아니라, print! 섹션에서 다룬 것처럼 해당 타입을 출력할 수 있게 해줍니다.

use std::fmt;

struct Circle {
    radius: i32
}

impl fmt::Display for Circle {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "반지름이 {}인 원", self.radius)
    }
}

fn main() {
    let circle = Circle { radius: 6 };
    println!("{}", circle.to_string());
}

문자열 파싱하기

문자열을 여러 타입으로 변환하는 것은 유용하지만, 가장 흔한 작업 중 하나는 문자열을 숫자로 변환하는 것입니다. 이에 대한 관용적인 방법은 parse 함수를 사용하는 것이며, 타입 추론을 이용하거나 ‘turbofish’ 구문을 사용하여 파싱할 타입을 지정할 수 있습니다. 다음 예제에 두 가지 방식이 모두 나와 있습니다.

해당 타입에 대해 FromStr 트레이트가 구현되어 있다면 문자열을 지정된 타입으로 변환합니다. 표준 라이브러리의 수많은 타입에 대해 이 트레이트가 구현되어 있습니다.

fn main() {
    let parsed: i32 = "5".parse().unwrap();
    let turbo_parsed = "10".parse::<i32>().unwrap();

    let sum = parsed + turbo_parsed;
    println!("합계: {:?}", sum);
}

사용자 정의 타입에서 이 기능을 사용하려면 해당 타입에 대해 FromStr 트레이트를 구현하기만 하면 됩니다.

use std::num::ParseIntError;
use std::str::FromStr;

#[derive(Debug)]
struct Circle {
    radius: i32,
}

impl FromStr for Circle {
    type Err = ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().parse() {
            Ok(num) => Ok(Circle{ radius: num }),
            Err(e) => Err(e),
        }
    }
}

fn main() {
    let radius = "    3 ";
    let circle: Circle = radius.parse().unwrap();
    println!("{:?}", circle);
}