What does the box keyword do?

前端 未结 3 1377
故里飘歌
故里飘歌 2021-02-01 12:27

In Rust, we can use the Box type to allocate things on the heap. This type is used to safely abstract pointers to heap memory. Box

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 13:25

    box does exactly what Box::new() does - it creates an owned box.

    I believe that you can't find implementation of box keyword because currently it is hardcoded to work with owned boxes, and Box type is a lang item:

    #[lang = "owned_box"]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[fundamental]
    pub struct Box(Unique);
    

    Because it is a lang item, the compiler has special logic to handle its instantiation which it can link with box keyword.

    I believe that the compiler delegates box allocation to functions in alloc::heap module.

    As for what box keyword does and supposed to do in general, Shepmaster's answer describes perfectly.

提交回复
热议问题