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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 28, 2023 (edit).