Arrays

Contents
Fixed-size arrays
Indexing
Length
Out of bounds panics

Fixed-size arrays

An array holds a fixed number of values that all share one type.

List the elements in brackets, or repeat one value with a semicolon count.

fn main() { let nums = [1, 2, 3]; let zeros = [0; 4]; println!("{:?} {:?}", nums, zeros); }

cargo run

[1, 2, 3] [0, 0, 0, 0]

Indexing

Read an element by its position in brackets, counting from zero.

Indexes work in expressions too, so values can be printed, copied, or combined directly.

fn main() { let nums = [10, 20, 30]; println!("{} {}", nums[0], nums[2]); }

cargo run

10 30

Length

The len method reports how many elements the array holds.

Since the size is fixed at compile time, the result never changes while the program runs.

fn main() { let nums = [10, 20, 30]; println!("{}", nums.len()); }

cargo run

3

Out of bounds panics

Direct indexing checks the range at run time and panics when the index is outside the array.

Prefer get for risky positions: it returns Some value on success and None when nothing is there.

fn main() { let nums = [1, 2, 3]; match nums.get(10) { Some(value) => println!("{}", value), None => println!("missing"), } }

cargo run

missing

Next: Vectors

Article author: Arthur Isaev

Related articles
Rust
Rust course: zero to hero in 50 lessons
What is Rust and where it runs
Install Rust
cargo new
Your first program
Variables
Numbers
Strings
Booleans
Tuples
Arrays
Vectors
Slices
if and else
match
Loops
Ownership
Borrowing
Lifetimes
Functions
Structs
Enums in Rust
Advanced match in Rust
Option combinators in Rust
Result and the question mark in Rust
Advanced strings in Rust
Vec methods in Rust
HashMaps in Rust
Modules in Rust
Crates and workspaces in Rust
Testing in Rust
Error handling
Traits
Generics
Trait bounds
Closures
Iterators
Smart pointers
Threads
Mutex and Arc
Files
CLI arguments
Environment variables
Diagnostics
Time
Parsing strings
TCP networking
Capstone: wordfreq CLI
Capstone: tiny HTTP server
Modern Rust tour
Hero roadmap: the whole course on one page
Install Rust on Windows 11
Install Rust on Ubuntu
Install Rust on Rocky Linux
Install Rust on macOS
Install Rust on FreeBSD
Rust in Docker
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: