Default ํŠธ๋ ˆ์ž‡

Default ํŠธ๋ ˆ์ž‡์€ ์–ด๋–ค ํƒ€์ž…์— ๋Œ€ํ•œ ๊ธฐ๋ณธ๊ฐ’์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

#[derive(Debug, Default)]
struct Derived {
    x: u32,
    y: String,
    z: Implemented,
}

#[derive(Debug)]
struct Implemented(String);

impl Default for Implemented {
    fn default() -> Self {
        Self("John Smith".into())
    }
}

fn main() {
    let default_struct = Derived::default();
    println!("{default_struct:#?}");

    let almost_default_struct = Derived {
        y: "Y is set!".into(),
        ..Derived::default()
    };
    println!("{almost_default_struct:#?}");

    let nothing: Option<Derived> = None;
    println!("{:#?}", nothing.unwrap_or_default());
}
  • ํŠธ๋ ˆ์ž‡์„ ์ง์ ‘ ๊ตฌํ˜„ํ•˜๊ฑฐ๋‚˜ #[derive(Default)]๋ฅผ ๋ถ™์—ฌ์„œ ์ปดํŒŒ์ผ๋Ÿฌ์—๊ฒŒ ๊ตฌํ˜„์„ ๋งก๊ธธ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ์ œ๊ณตํ•˜๋Š” ์ž๋™ ๊ตฌํ˜„์˜ ๊ฒฝ์šฐ ๋ชจ๋“  ํ•„๋“œ์— ๋Œ€ํ•ด ๊ธฐ๋ณธ ๊ฐ’์„ ์„ค์ •ํ•œ ์ƒˆ ์ธ์Šคํ„ด์Šค๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
    • ์ด๋Š” ๊ตฌ์กฐ์ฒด์˜ ๊ฐ ํ•„๋“œ ํƒ€์ž…๋“ค์ด ๋ชจ๋‘ Default ํŠธ๋ ˆ์ž‡์„ ๊ตฌํ˜„ํ•ด์•ผ ํ•จ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.
  • ๋Ÿฌ์ŠคํŠธ ํ‘œ์ค€ ํƒ€์ž…๋“ค์€ ๋Œ€๋ถ€๋ถ„ Default๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ์œผ๋ฉฐ, ๊ธฐ๋ณธ ๊ฐ’์€ 0์ด๋‚˜ ""์ฒ˜๋Ÿผ ์˜ˆ์ƒ ๊ฐ€๋Šฅํ•œ ๊ฐ’๋“ค์ž…๋‹ˆ๋‹ค.
  • ๊ตฌ์กฐ์ฒด์˜ ์ผ๋ถ€๋ถ„๋งŒ ๋ณต์‚ฌํ•˜๊ณ  ์‹ถ์„ ๋•Œ default๋ฅผ ํŽธ๋ฆฌํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ๋Ÿฌ์ŠคํŠธ ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” Default ํŠธ๋ ˆ์ž‡์„ ๊ตฌํ˜„ํ•œ ํƒ€์ž…์„ ์œ„ํ•œ ํŽธ์˜ ๋ฉ”์„œ๋“œ๋ฅผ ์ œ๊ณตํ•˜๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค.
  • ์ด .. ๋ฌธ๋ฒ•์€ ๊ตฌ์กฐ์ฒด ์—…๋ฐ์ดํŠธ ๋ฌธ๋ฒ•(struct update syntax)๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค