Rust: From Into - grizlupo/_ GitHub Wiki

ํ˜•์„ ๋ฐ”๊พธ๋Š” ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•์œผ๋กœ ์ œ๊ณต๋˜๋Š” ๊ฒƒ์ด From๊ณผ Into๋‹ค.

์šฐ์„  From์€ ์ƒˆ๋กœ์šด ํ˜•์„ ์ •์˜ํ•  ๋•Œ ๊ธฐ์กด์˜ ๋‹ค๋ฅธ ํ˜•๋“ค์„ ์ •์˜ํ•˜๋Š” ํ˜•์œผ๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋„๋ก ํ•ด ์ค€๋‹ค.

use std::convert::From;

#[derive(Debug)]
struct Me {
    value: i32
}

impl From<i32> for Me {
    fn from(value: i32) -> Self {
        Self { value }
    }
}

fn main() {
    println!("{:?}", Me::from(10));
}

Run

์ •๋ง์ด์ง€ ์“ธ๋ฐ ์—†์–ด ๋ณด์ด๋Š” ์˜ˆ์ œ์ง€๋งŒ ๋ญ ์ด๋Ÿฐ ์‹์ด๋‹ค.

๊ฒฐ๊ณผ๋Š” Me { value: 10 }

๋ฐ˜๋Œ€๋กœ ์ƒˆ ํ˜•์„ ๋‹ค๋ฅธ ํ˜•์œผ๋กœ ๋ฐ”๊พธ๊ณ  ์‹ถ์œผ๋ฉด

#![allow(unused)]
use std::convert::From;

#[derive(Debug)]
struct Me {
    value: i32
}

impl From<Me> for String {
    fn from(me: Me) -> String {
        format!("value: {}", me.value)
    }
}

fn main() {
    println!("{}", String::from(Me { value: 10 }));
}

Run

๊ฒฐ๊ณผ๋Š” value: 10

๊ทธ๋Ÿผ Into๋Š” ๋ญ”๊ฐ€?

1.41 ์ด์ „ ๋ฒ„์ „์€ ๋ชฉํ‘œํ˜•์ด ํ˜„์žฌ crate์ด ์•„๋‹ˆ๋ฉด From์„ ์ •์˜ํ•  ์ˆ˜ ์—†์—ˆ๋‹ค๊ณ  ํ•œ๋‹ค. ๊ทธ๋ž˜์„œ impl From<Me> for String ์ด๋ ‡๊ฒŒ ํ•  ์ˆ˜๋Š” ์—†๊ณ , Me๊ฐ€ Into๋ฅผ ์ •์˜ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ํ•ด์•ผ ํ•œ๋‹ค. ์ด ์˜ˆ์ œ๋ฅผ ๋งŒ๋“œ๋Š” ์‹œ์ ์— Rust๋Š” ์•ˆ์ • ๋ฒ„์ „์ด ์ด๋ฏธ 1.45.1์ด๊ธฐ ๋•Œ๋ฌธ์— ์•ˆ๋˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜๊ฐ€ ์—†๋‹ค. ๊ทธ๋ ‡์ง€๋งŒ ๋ฌธ์„œ๋Š” ์ด๋Ÿฐ ๊ฒฝ์šฐ์—๋Š” Into๋กœ ํ•˜๋ผ๊ณ  ํ•˜๊ณ  ์žˆ๋‹ค.

use std::convert::Into;

#[derive(Debug)]
struct Me {
    value: i32
}

impl Into<String> for Me {
    fn into(self) -> String {
        format!("value: {}", self.value)
    }
}

fn main() {
    let s: String = (Me { value: 10 }).into();
    println!("{}", s);
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ