Box<T>

Box๋Š” ํž™ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์†Œ์œ  ํฌ์ธํ„ฐ์ž…๋‹ˆ๋‹ค:

fn main() {
    let five = Box::new(5);
    println!("five: {}", *five);
}
5StackHeapfive

Box<T>์€ Deref<Target = T>๋ฅผ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” Box<T>์—์„œ T ๋ฉ”์„œ๋“œ๋ฅผ ์ง์ ‘ ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค.

์žฌ๊ท€ ๋ฐ์ดํ„ฐ๋‚˜ ๋™์ ํฌ๊ธฐ์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์€ Boxํƒ€์ž…์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค:

#[derive(Debug)]
enum List<T> {
    /// A non-empty list: first element and the rest of the list.
    Element(T, Box<List<T>>),
    /// An empty list.
    Nil,
}

fn main() {
    let list: List<i32> =
        List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
    println!("{list:?}");
}
StackHeaplistElement1Element2Nil
This slide should take about 8 minutes.
  • Box is like std::unique_ptr in C++, except that itโ€™s guaranteed to be not null.

  • Box๋Š” ์•„๋ž˜์˜ ๊ฒฝ์šฐ์— ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค:

    • ํƒ€์ž… ํฌ๊ธฐ๋ฅผ ์ปดํŒŒ์ผ ์‹œ์ ์— ์•Œ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ.
    • ์•„์ฃผ ํฐ ๋ฐ์ดํ„ฐ์˜ ์†Œ์œ ๊ถŒ์„ ์ „๋‹ฌํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ. ์Šคํƒ์— ์žˆ๋Š” ํฐ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณต์‚ฌํ•˜๋Š” ๋Œ€์‹  Box๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋Š” ํž™์— ์ €์žฅํ•˜๊ณ  ํฌ์ธํ„ฐ๋งŒ ์ด๋™ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.
  • If Box was not used and we attempted to embed a List directly into the List, the compiler would not be able to compute a fixed size for the struct in memory (the List would be of infinite size).

  • Box๋Š” ์ผ๋ฐ˜ ํฌ์ธํ„ฐ์™€ ํฌ๊ธฐ๊ฐ€ ๊ฐ™๊ธฐ ๋•Œ๋ฌธ์— ํฌ๊ธฐ๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐ ๋ฌธ์ œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ ํž™์— ์œ„์น˜ํ•œ List์˜ ๋‹ค์Œ ์š”์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚ฌ ๋ฟ์ž…๋‹ˆ๋‹ค.

  • Remove the Box in the List definition and show the compiler error. We get the message โ€œrecursive without indirectionโ€, because for data recursion, we have to use indirection, a Box or reference of some kind, instead of storing the value directly.

๋” ์‚ดํŽด๋ณด๊ธฐ

๋‹ˆ์น˜(ํ‹ˆ์ƒˆ) ์ตœ์ ํ™”(Niche Optimization)

#[derive(Debug)]
enum List<T> {
    Element(T, Box<List<T>>),
    Nil,
}

fn main() {
    let list: List<i32> =
        List::Element(1, Box::new(List::Element(2, Box::new(List::Nil))));
    println!("{list:?}");
}

Box๋Š” ๋น„์–ด์žˆ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ํฌ์ธํ„ฐ๋Š” ํ•ญ์ƒ ์œ ํšจํ•˜๋ฉฐ null์ด ์•„๋‹™๋‹ˆ๋‹ค. ์ด๋Š” ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ ๋ ˆ์ด์•„์›ƒ์„ ์ตœ์ ํ™” ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค๋‹ˆ๋‹ค:

StackHeaplistElement1Element2