Box<T>
Box
๋ ํ ๋ฐ์ดํฐ์ ๋ํ ์์ ํฌ์ธํฐ์
๋๋ค:
fn main() { let five = Box::new(5); println!("five: {}", *five); }
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:?}"); }
-
Box
is likestd::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 aList
directly into theList
, the compiler would not be able to compute a fixed size for the struct in memory (theList
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, aBox
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
์ด ์๋๋๋ค. ์ด๋ ์ปดํ์ผ๋ฌ๊ฐ ๋ฉ๋ชจ๋ฆฌ ๋ ์ด์์์ ์ต์ ํ ํ ์ ์๊ฒ ํด์ค๋๋ค: