Allocate array onto heap with size known at runtime

后端 未结 1 416
轻奢々
轻奢々 2021-01-12 06:34

In C++, I could put an array of 1000 ints onto the heap like this:

int size = 1000;
int* values = new in         


        
1条回答
  •  余生分开走
    2021-01-12 07:07

    Arrays in Rust are fixed-length. If you want a dynamically-sized array, use Vec. In this case, the simplest way is with the vec! macro:

    let size = 1000;
    let values = vec![0; size];
    

    Also, if you're super concerned about Vec being three words long and don't need to resize the storage after it's created, you can explicitly discard the internal capacity, and bring values down to two words on the stack:

    let values = values.into_boxed_slice(); // returns a Box<[i32]>.
    

    0 讨论(0)
提交回复
热议问题