Module 3 · Borrowing & slices
3.2Slices: &str and &[T]
How Rust borrows part of a string or a list without copying it, the difference between String and &str, and what the 'static in &'static str means.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Part of a list | scores.slice(1, 4) copies into a new array | scores[1..4] copies; scores.AsSpan(1..4) is a view | &scores[1..4] is a view: no copy |
| Part of a string | text.slice(0, 5) returns a new string | text[..5] copies; text.AsSpan(..5) is a view | &text[..5] is a view: no copy |
| Text types | One type: string | string, plus ReadOnlySpan<char> for views | String owns and can grow; &str borrows |
| A string literal | string | string (interned) | &'static str: a borrow of text stored in the program itself |
| What a string index counts | UTF-16 code units | UTF-16 code units (char) | Bytes of UTF-8; slicing inside a character panics |
| Count from the end | slice(-2) | [^2..] | [len - 2..]; there are no negative or ^ indexes |
The previous lesson lent a whole value with &. A slice lends part of one: a run of elements inside a Vec or an array, or a run of text inside a String. A slice doesn’t copy anything. It’s a pointer to the first element plus a length, and the borrow checker makes sure the data it points at stays put while you use it. In TypeScript, slice on an array or a string gives you a new array or string, not a view of the original; the nearest thing to a Rust slice is a typed array’s subarray(), which views the same buffer. Rust uses views like that everywhere.If you’ve used C#‘s Span<T> or ReadOnlySpan<char>, you already know the idea; Rust just uses it everywhere.
A slice is a view, not a copy
Here’s a program that adds up the middle three scores. TypeScript’s slice copies them into a new array. Rust’s &scores[1..4] doesn’t copy: it points into the original.C#‘s AsSpan and Rust’s &scores[1..4] don’t copy: they point into the original.
const scores = [10, 20, 30, 40, 50];
const middle = scores.slice(1, 4); // a new array with 3 numbers
const total = middle.reduce((sum, score) => sum + score, 0);
console.log(`${middle.length} scores, total ${total}`);int[] scores = [10, 20, 30, 40, 50];
ReadOnlySpan<int> middle = scores.AsSpan(1..4); // a view: no copy
var total = 0;
foreach (var score in middle)
{
total += score;
}
Console.WriteLine($"{middle.Length} scores, total {total}");let scores = [10, 20, 30, 40, 50];
let middle: &[i32] = &scores[1..4]; // a view: no copy
let total: i32 = middle.iter().sum();
println!("{} scores, total {total}", middle.len());Output
3 scores, total 90
&scores[1..4] reads as “borrow elements 1 up to, but not including, 4”. Its type is &[i32]: a slice of i32. It works like a read-only array: len(), indexing, iter() and loops all work on it.
Strings work the same way. This function returns the first word of some text without copying it, where TypeScript’s slice gives you a new string. The C# version uses ReadOnlySpan<char> to get the same zero-copy behavior:
function firstWord(text: string): string {
const end = text.indexOf(" ");
return end === -1 ? text : text.slice(0, end);
}
const greeting = "hello world";
console.log(firstWord(greeting));
console.log(firstWord("good morning"));var greeting = "hello world";
Console.WriteLine(FirstWord(greeting).ToString());
Console.WriteLine(FirstWord("good morning").ToString());
static ReadOnlySpan<char> FirstWord(ReadOnlySpan<char> text)
{
var end = text.IndexOf(' ');
return end == -1 ? text : text[..end];
}fn first_word(text: &str) -> &str {
let end = text.find(' ').unwrap_or(text.len()); // index of the first space, or the end
&text[..end]
}
fn main() {
let greeting = String::from("hello world");
println!("{}", first_word(&greeting));
println!("{}", first_word("good morning"));
}Output
hello good
The returned &str points into greeting’s buffer. The compiler knows that, so it won’t let greeting be changed or dropped while the word is still in use.
Mental model shiftref struct rules are a small borrow checker
A Span<T> is a ref struct, so C# restricts it: it can’t be a field of a class, can’t be boxed, can’t be captured by a lambda and can’t live across an await. The scoped keyword stops a span parameter from escaping the method. All of that exists so a span never outlives the memory it points at. Rust applies the same kind of check to every reference and every slice, so you get spans’ zero-copy speed without a separate set of rules.
String vs &str, Vec<T> vs &[T]
This is the confusion everyone coming from TypeScriptC# hits, because TypeScriptC# has one string type. Rust has two, and they split the job:
Stringowns its text. It’s a growable buffer on the heap, like a C#StringBuilderthat you can also read. You canpush_stronto it, and when it goes out of scope, its buffer is freed.&strborrows text that something else owns: all of aString, part of one, or a literal. It can’t grow and doesn’t free anything.
Vec<T> and &[T] are the same pair for lists: Vec<T> owns a growable buffer, &[T] borrows a run of elements from a Vec, an array or another slice.
Getting from one to the other is easy in one direction and costs an allocation in the other:
let owned = String::from("Ada"); // &str -> String: allocates and copies
let borrowed: &str = &owned; // String -> &str: free, just a borrow
let again = borrowed.to_string(); // &str -> String: allocates and copies
let list = vec![1, 2, 3];
let view: &[i32] = &list; // Vec<i32> -> &[i32]: free
let copy = view.to_vec(); // &[i32] -> Vec<i32>: allocates and copies&owned has the type &String, but where a &str is expected Rust converts it for you. This is called deref coercion, and it’s why first_word(&greeting) works above. &Vec<T> becomes &[T] the same way. An array reference, &[T; N], also converts to &[T] automatically (strictly, an unsizing coercion rather than a deref, but it looks the same at the call site).
Idiomatic RustTake &str and &[T], not &String and &Vec
A parameter of type &str accepts a &String, a literal and a slice of either. A parameter of type &String only accepts a &String, so callers with a literal have to allocate a String first:
fn shout(text: &String) -> String {
text.to_uppercase()
}
fn main() {
println!("{}", shout("hello"));
}Rust doesn't compile this: error E0308
error[E0308]: mismatched types
--> main.rs:6:26
|
6 | println!("{}", shout("hello"));
| ----- ^^^^^^^ expected `&String`, found `&str`
| |
| arguments to this function are incorrect
|
= note: expected reference `&String`
found reference `&'static str`
note: function defined here
--> main.rs:1:4
|
1 | fn shout(text: &String) -> String {
| ^^^^^ -------------Change the parameter to text: &str and both shout("hello") and shout(&name) work. The same goes for lists: take &[T], not &Vec<T>. Clippy flags &String and &Vec<T> parameters with the ptr_arg lint.
String literals are &'static str
A literal like "good morning" has the type &'static str. The text is stored inside your compiled program, next to the code, and loaded with it. A literal is a borrow of that text.
The ' introduces a lifetime: a name for how long a borrow is valid. Most of the time Rust works lifetimes out and you never write them. 'static is the one you’ll see early, and it means valid for the whole run of the program. That’s true for a literal because the text is part of the program: nobody allocated it and nobody frees it.
Here’s where the bytes live for a literal and for a String made from it:
let label: &'static str = "ok";
let owned = String::from(label);
println!("{label} {owned}");label borrows text that the program carries with it, which is why the borrow is 'static. owned has its own copy on the heap, freed when owned goes out of scope.
That’s useful when a function picks one of a few fixed strings. It can return &'static str and nothing is allocated:
function statusLabel(code: number): string {
return code === 404 ? "not found" : "ok";
}
console.log(statusLabel(200));
console.log(statusLabel(404));Console.WriteLine(StatusLabel(200));
Console.WriteLine(StatusLabel(404));
static string StatusLabel(int code) => code == 404 ? "not found" : "ok";fn status_label(code: u16) -> &'static str {
if code == 404 { "not found" } else { "ok" }
}
fn main() {
println!("{}", status_label(200));
println!("{}", status_label(404));
}Output
ok not found
Don’t confuse the lifetime 'static with the keyword static:
static APP_NAME: &str = "binshelf"; // a static item: one global value
fn banner() -> String {
format!("Welcome to {APP_NAME}")
}
fn main() {
let version: &'static str = "1.0"; // a local variable holding a 'static borrow
println!("{} {version}", banner());
}'static(with an apostrophe) describes how long a borrow is valid.versionis an ordinary local variable; the text it points at lives forever.static(a keyword) declares a global item with one fixed address, like a global variable. Its type here is&'static str.- You’ll later meet
'staticas a bound, writtenT: 'static, for example on the closurestd::thread::spawnaccepts. That’s weaker than&'static: it means the type holds no borrows that could expire, so an ownedStringqualifies even though it’s freed when its owner is done. Module 11 covers it. - TypeScript’s
staticmeans something else again: a class member that belongs to the class instead of an instance. The closest TypeScript match for a Ruststaticitem is a module-levelconst.C#‘sstaticmeans something else again: a member that belongs to a type instead of an instance. The closest C# match for a Ruststaticitem is astatic readonlyfield. Rust types have no static fields; associated constants and functions withoutself(likeString::from) play that role. Structs & impl blocks covers them.
Ranges and indexes
Rust slices with ranges. The end is excluded unless you write ..=:
let scores = [10, 20, 30, 40, 50];
let all = &scores[..]; // [10, 20, 30, 40, 50]
let first_two = &scores[..2]; // [10, 20]
let from_third = &scores[2..]; // [30, 40, 50]
let middle = &scores[1..4]; // [20, 30, 40]
let inclusive = &scores[1..=3]; // [20, 30, 40]
let last_two = &scores[scores.len() - 2..]; // [40, 50]
println!("{middle:?} {last_two:?}");There are no negative indexes as in TypeScript’s slice(-2) and no ^2 as in C#; count from len(). A range outside the data panics, where TypeScript’s slice silently returns fewer items, like C#‘s ArgumentOutOfRangeException. If a range might not fit, scores.get(3..10) returns None instead of panicking.
String indexes count bytes, not characters. Rust strings are UTF-8, so "é" takes two bytes and "🦀" takes four. &text[0..2] means “the first two bytes”, and if that cuts a character in half, the program panics. TypeScriptC# counts UTF-16 code units instead; there, cutting an emoji in half doesn’t fail, it silently produces a broken character. Module 8 covers strings and characters in depth.
Which one should I use?
For text, the choice comes down to two questions, asked in order:
Do you only read text that something else owns, as in almost every parameter?
YesNoBorrow it:
&strAccepts a&String, a literal and a slice of either, with no copy.Is the text fixed when you compile, like a literal, a label or a message?
YesNoUse
&'static strIt lives for the whole program, so you can return it or store it with no allocation.Otherwise: You build, change or keep the text (a struct field, a value you return, text you
push_stronto): own it withString
Lists follow the same pattern: &[T] to read, Vec<T> to own, and [T; N] for a fixed number of items.
| What | When | Why | How |
|---|---|---|---|
String | You build, change or keep text: a struct field, a value you return, text you push_str onto. | It owns its buffer, so it can grow and it lives as long as you need it. | String::from("Ada"), "Ada".to_string(), format!(...). Return it from functions that build text. |
&str | You only read text: almost every parameter. | Accepts a String (as &name), a literal and a slice of either. No copy, no allocation. | fn greet(name: &str); call greet(&name) or greet("Ada"). |
&'static str | Text that’s fixed when you compile: literals, labels, messages. | Lives for the whole program, so you can return it or store it anywhere with no allocation. | Write a literal. Return &'static str from a function that picks among literals. |
Vec<T> | You build, grow or keep a list. | It owns its buffer and can push, pop and grow. | vec![1, 2, 3], Vec::new(), .collect(). Use it for struct fields and return values. |
&[T] | You only read a list, or part of one: almost every list parameter. | Accepts a Vec, an array or a range of either, with no copy. Use &mut [T] to change elements without changing the length. | fn total(scores: &[i32]); call total(&scores) or total(&scores[1..4]). |
[T; N] | A fixed number of items known at compile time: an RGB color, a 3×3 grid. | Lives inline (on the stack or inside a struct), with no heap allocation. | let rgb = [255, 128, 0];. Pass &rgb where a &[T] is expected. |
Rule of thumb: own with String and Vec<T> (fields, return values, things you build), borrow with &str and &[T] (parameters, read-only views). If you’re tempted to write &String or &Vec<T>, write &str or &[T].
Under the hood
A slice is a fat pointer: two machine words, a pointer to the first element and a length. A String or Vec is three: pointer, length and capacity. A plain reference like &String is one.
println!("String: {} bytes", size_of::<String>());
println!("&str: {} bytes", size_of::<&str>());
println!("&String: {} bytes", size_of::<&String>());On a 64-bit machine, that prints 24, 16 and 8. Drawn to scale, one byte per column:
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
String | ptr8 bytes · pointer | len8 bytes | capacity8 bytes | 24 bytes | |||||||||||||||||||||
&str | ptr8 bytes · pointer | len8 bytes | 16 bytes | ||||||||||||||||||||||
&String | ptr8 bytes · pointer | 8 bytes | |||||||||||||||||||||||
Three rows drawn to scale, today, on a 64-bit target. String is 24 bytes: an 8-byte pointer to its heap buffer, an 8-byte length and an 8-byte capacity. &str is 16 bytes: an 8-byte pointer to the first byte of the text and an 8-byte length, with no capacity because a slice can't grow. &String is 8 bytes: one pointer to the String, which holds the length itself.
&str and &[T] are always two words and &String is always one; String’s three words aren’t formally guaranteed, but that’s the layout today. Vec<T> and &[T] have the same shapes as String and &str. Here’s first_word’s idea from the other end: a slice of the second word of "hello world".
let text = String::from("hello world");
let word = &text[6..];
println!("{word}");word has no capacity because it can’t grow, and it doesn’t free anything when it goes out of scope. A string literal looks the same, except its pointer leads into the program’s read-only data instead of the heap.
Common pitfalls
Common pitfallA literal isn't a String
In TypeScriptC#, a literal is a string like any other. In Rust, "Ada" is a &str, so it doesn’t fit where a String is expected:
let name: String = "Ada";Rust doesn't compile this: error E0308
error[E0308]: mismatched types --> main.rs:1:20 | 1 | let name: String = "Ada"; | ------ ^^^^^ expected `String`, found `&str` | | | expected due to this | help: try using a conversion method | 1 | let name: String = "Ada".to_string(); | ++++++++++++
Convert it with String::from("Ada") or "Ada".to_string(). Going the other way, from a String to a &str, is just &name.
Common pitfallSlicing inside a character panics
String slices use byte positions. In "héllo", the é takes bytes 1 and 2, so ending a slice at byte 2 cuts it in half:
let word = "héllo";
let start = &word[0..2];
println!("{start}");This compiles, then panics at run time with “byte index 2 is not a char boundary; it is inside ‘é’ (bytes 1..3)”. Use word.get(0..2), which returns None instead, or work with characters through word.chars(). Indexes that come from find or char_indices are always on a boundary.
Common pitfallA slice freezes what it points into
While a slice exists, you can’t change the String or Vec it borrows from, because a push might move the buffer. This is the many-readers-or-one-writer rule from References:
let mut text = String::from("hello world");
let word = &text[..5];
text.push_str("!");
println!("{word}");Rust doesn't compile this: error E0502
error[E0502]: cannot borrow `text` as mutable because it is also borrowed as immutable
--> main.rs:3:1
|
2 | let word = &text[..5];
| ---- immutable borrow occurs here
3 | text.push_str("!");
| ^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
4 | println!("{word}");
| ---- immutable borrow later used hereFinish with the slice first, or copy what you need with .to_string() before changing the original.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. Write one report function and call it with a whole list, the first three items of that list, and a fixed-size array. Pass the first two names as literals and the last as a String.
function report(name: string, scores: readonly number[]): string {
const total = scores.reduce((sum, score) => sum + score, 0);
return `${name}: ${total}`;
}
const scores = [10, 20, 30, 40, 50];
const bonus = [5, 5];
const bonusName = "bonus";
console.log(report("all", scores));
console.log(report("first three", scores.slice(0, 3)));
console.log(report(bonusName, bonus));List<int> scores = [10, 20, 30, 40, 50];
int[] bonus = [5, 5];
var bonusName = "bonus";
Console.WriteLine(Report("all", scores));
Console.WriteLine(Report("first three", scores[..3])); // a copy
Console.WriteLine(Report(bonusName, bonus));
static string Report(string name, IReadOnlyList<int> scores) => $"{name}: {scores.Sum()}";Expected output
all: 150 first three: 60 bonus: 10
Show a hint
Make report take name: &str and scores: &[i32]. Pass &scores for the whole Vec, &scores[..3] for the first three, &bonus for the array, and &bonus_name for the String.
Show a solution
fn report(name: &str, scores: &[i32]) -> String {
let total: i32 = scores.iter().sum();
format!("{name}: {total}")
}
fn main() {
let scores = vec![10, 20, 30, 40, 50];
let bonus = [5, 5];
let bonus_name = String::from("bonus");
println!("{}", report("all", &scores));
println!("{}", report("first three", &scores[..3]));
println!("{}", report(&bonus_name, &bonus));
}One function covers every caller: a Vec, part of a Vec and an array all coerce to &[i32], and a literal and a String both work as &str. Nothing is copied; only report allocates, for the String it returns.
Saved in this browser only.