Book Image

Rust Essentials

By : Ivo Balbaert
Book Image

Rust Essentials

By: Ivo Balbaert

Overview of this book

<p>Starting by comparing Rust with other programming languages, this book will show you where and how to use Rust. It will discuss primitive types along with variables and their scope, binding and casting, simple functions, and ways to control execution flow in a program.</p> <p>Next, the book covers flexible arrays, vectors, tuples, enums, and structs. You will then generalize the code with higher-order functions and generics applying it to closures, iterators, consumers, and so on. Memory safety is ensured by the compiler by using references, pointers, boxes, reference counting, and atomic reference counting. You will learn how to build macros and crates and discover concurrency for multicore execution.</p> <p>By the end of this book, you will have successfully migrated to using Rust and will be able to use it as your main programming language.</p>
Table of Contents (17 chapters)
Rust Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Arrays, vectors, and slices


Suppose we have a bunch of alien creatures to populate a game level, then we would probably want to store their names in a handy list. Rust's array is just what we need:

// from Chapter 4/code/arrays.rs
let aliens = ["Cherfer", "Fynock", "Shirack", "Zuxu"];
println!("{:?}", aliens);

To make an array, separate the different items by commas and enclose the whole thing within [ ] (rectangular brackets). All the items must be of the same type. Such an array must be of a fixed size (this must be known at compile time) and cannot be changed; this is stored in one contiguous piece of memory.

If the items have to be modifiable, declare your array with let mut; however, even then the number of items cannot change. The aliens array could be of the type that is annotated as [&str; 4] where the first parameter is the type of the items and the second is their number:

let aliens: [&str; 4] = ["Cherfer", "Fynock", "Shirack", "Zuxu"];

If we want to initialize an array with...