Skip to the workspace
Pebellslearn by building
Language Basics  ›  Lesson

Strings, Tuples and Arrays

String 12 minString is owned, growable text while &str is a borrowed view of text, a tuple groups a fixed set of values of different types, and an array holds a fixed number of values of one type.

rust / Strings, Tuples and Arrays

Explore each scene at your own pace.

01 · The rule

The rule

Strings, Tuples and Arrays

String is owned, growable text while &str is a borrowed view of text, a tuple groups a fixed set of values of different types, and an array holds a fixed number of values of one type.

Compare owned text, borrowed text, fixed tuples and fixed-size arrays.

A catalogue entry is more than one number. It has a title (text), maybe a title and page count travelling together, and a week of daily loan counts. Rust has a specific type for each shape, and text comes in two kinds that everyone mixes up at first.

The rule

String owns text, &str borrows it; tuples mix types, arrays repeat one.

String is text the variable owns. It lives on the heap and can grow.

let mut title = String::from("Iron Tides");
title.push_str(" (2nd edition)");

&str (a "string slice") is a borrowed view into text stored somewhere else. Every literal in quotes is a &str, and it is read-only.

let shelf_name: &str = "Fiction";
let first_word: &str = &title[0..4];   // "Iron"

Convert between them: "Fiction".to_string() or String::from(...) makes a String; &title gives a &str view of a String. Functions that only read text should take &str, so they accept both.

Strings are UTF-8, so .len() counts bytes, not characters. "café".len() is 5. Walk characters with .chars(). For the same reason you cannot write title[0]; Rust forbids indexing a string by position.

Tuples group a fixed number of values that may differ in type. Read them by position:

let entry: (&str, u32) = ("Night Garden", 288);
println!("{} has {} pages", entry.0, entry.1);

Arrays hold a fixed number of values of one type. The length is part of the type:

let week: [u32; 7] = [4, 2, 5, 3, 6, 9, 1];
let monday = week[0];
let blank = [0; 7];            // seven zeros

Indexing past the end, like week[7], panics instead of reading stray memory.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.