Stringとの型変換 - Rust By Example
Description: Rust by Example (RBE) is a collection of runnable examples that illustrate various Rust concepts and standard libraries.

## 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への型変換

To convert any type to a `String` is as simple as implementing the `ToString` trait for the type. Rather than doing so directly, you should implement the `fmt::Display` trait which automatically provides `ToString` and also allows printing the type as discussed in the section on `print!`.

    use std::fmt;

    struct Circle {
        radius: i32
    }

    impl fmt::Display for Circle {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "Circle of radius {}", self.radius)
        }
    }

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

## Stringの解析

文字列からの型変換において、数値への型変換はよく行われるものの一つです。これを行うイディオムは`parse`関数を使用することですが、このときに型を推論できるようにするか、もしくはターボフィッシュ構文（`::<>`）を使用して型を指定するかのいずれかを行います。以下の例では、どちらの方法も紹介しています。

This will convert the string into the type specified as long as the `FromStr` trait is implemented for that type. This is implemented for numerous types within the standard library.

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

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

To obtain this functionality on a user defined type simply implement the `FromStr` trait for that type.

    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);
    }