Initialize array. In Rust programs we have arrays, slices, and vectors and they often can be used interchangeably. We can initialize them with a variety of syntax forms.
With an array or vector, if we take a reference, we can get a slice. The slice can be used as a type in function arguments for more versatile code.
Syntax examples. This example initializes vectors, slices and arrays in a variety of ways. For slices, we have to create a vector or array and take a reference to part of it.
Tip For a String vector, make sure to use to_string(). String literals are "str" references, not Strings.
Also For arrays, we specify a value and the number of repetitions in square brackets.
Finally For vectors, we can use methods like push() to append to a vector, or extend_from_slice which is faster.
Get. The get() function is similar to taking a slice, but it returns an Option. To deal with the Option in the clearest way, we can use the if let Some syntax.
Summary. In Rust we can allocate vectors and arrays. For vectors, we often use the "vec" macro. And slices can take references to ranges of vectors and arrays in a unified way.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 28, 2023 (edit).