乐闻世界logo
搜索文章和话题

How to set a Rust array length dynamically?

1个答案

1

In Rust, arrays are data structures with fixed length. The length of an array is determined at compile time and cannot be modified once declared. This means you cannot dynamically change the array length at runtime.

If you need a data structure that can change size at runtime, you should use Vec<T>, which is a vector. A vector is a mutable array that can dynamically grow and shrink, making it suitable for scenarios requiring dynamic length.

The following is an example using Vec<T> to store integers and dynamically modify its length at runtime:

rust
fn main() { let mut numbers: Vec<i32> = Vec::new(); // Create a new empty vector // Add elements numbers.push(1); // Now the vector contains one element [1] numbers.push(2); // Now the vector contains two elements [1, 2] numbers.push(3); // Now the vector contains three elements [1, 2, 3] // Remove elements numbers.pop(); // Remove the last element, now the vector contains [1, 2] // You can also use with_capacity to pre-allocate space let mut preallocated_numbers: Vec<i32> = Vec::with_capacity(10); // Now this vector has pre-allocated space, but currently contains no elements for i in 0..10 { preallocated_numbers.push(i); } // This vector now contains 10 elements and has not undergone any reallocations println!("Numbers: {:?}", numbers); println!("Preallocated numbers: {:?}", preallocated_numbers); }

In this example, numbers is a vector of type Vec<i32> that can dynamically change its size. We use the push method to add elements and the pop method to remove elements. preallocated_numbers is another example where we use the with_capacity method to pre-allocate space, which helps reduce the number of memory reallocations when the vector grows.

It's worth noting that, unlike arrays, vectors have some performance overhead due to their dynamic nature. When you need to determine the array length at compile time and the length won't change, using an array is a better choice. If you need to dynamically modify the length, vectors are a better choice.

2024年6月29日 12:07 回复

你的答案