Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    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.

    About 25 minutesBeginner

    On this page
    1. Concept map
    2. A slice is a view, not a copy
    3. String vs &str, Vec<T> vs &[T]
    4. String literals are &'static str
    5. Ranges and indexes
    6. Which one should I use?
    7. Under the hood
    8. Common pitfalls
    9. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Part of a listscores.slice(1, 4) copies into a new arrayscores[1..4] copies; scores.AsSpan(1..4) is a view&scores[1..4] is a view: no copy
    Part of a stringtext.slice(0, 5) returns a new stringtext[..5] copies; text.AsSpan(..5) is a view&text[..5] is a view: no copy
    Text typesOne type: stringstring, plus ReadOnlySpan<char> for viewsString owns and can grow; &str borrows
    A string literalstringstring (interned)&'static str: a borrow of text stored in the program itself
    What a string index countsUTF-16 code unitsUTF-16 code units (char)Bytes of UTF-8; slicing inside a character panics
    Count from the endslice(-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.

    TypeScript
    scores.ts
    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}`);
    C#
    Scores.cs
    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}");
    Rust
    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:

    TypeScript
    firstWord.ts
    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"));
    C#
    FirstWord.cs
    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];
    }
    Rust
    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:

    • String owns its text. It’s a growable buffer on the heap, like a C# StringBuilder that you can also read. You can push_str onto it, and when it goes out of scope, its buffer is freed.
    • &str borrows text that something else owns: all of a String, 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}");
    A literal and a String made from itOn the stack, label is a &'static str: a pointer to the bytes o and k, which are stored in the program's read-only data, not on the heap, and a length of 2. Below it, owned is a String: a pointer to its own heap buffer holding a copy of the bytes o and k, a length of 2 and a capacity of 2. String::from copied the text; the literal's bytes stay in the program for its whole run, so a borrow of them is valid for the whole run too.StackRead-only data and heaplabel: &'static strptrlen2owned: Stringptrlen2capacity2read-only data in the binaryokheap bufferok
    A literal and a String made from it. On the stack, label is a &'static str: a pointer to the bytes o and k, which are stored in the program's read-only data, not on the heap, and a length of 2. Below it, owned is a String: a pointer to its own heap buffer holding a copy of the bytes o and k, a length of 2 and a capacity of 2. String::from copied the text; the literal's bytes stay in the program for its whole run, so a borrow of them is valid for the whole run too.

    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:

    TypeScript
    status.ts
    function statusLabel(code: number): string {
      return code === 404 ? "not found" : "ok";
    }
    
    console.log(statusLabel(200));
    console.log(statusLabel(404));
    C#
    Status.cs
    Console.WriteLine(StatusLabel(200));
    Console.WriteLine(StatusLabel(404));
    
    static string StatusLabel(int code) => code == 404 ? "not found" : "ok";
    Rust
    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. version is 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 'static as a bound, written T: 'static, for example on the closure std::thread::spawn accepts. That’s weaker than &'static: it means the type holds no borrows that could expire, so an owned String qualifies even though it’s freed when its owner is done. Module 11 covers it.
    • TypeScript’s static means something else again: a class member that belongs to the class instead of an instance. The closest TypeScript match for a Rust static item is a module-level const.C#‘s static means something else again: a member that belongs to a type instead of an instance. The closest C# match for a Rust static item is a static readonly field. Rust types have no static fields; associated constants and functions without self (like String::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:

    String, &str or &'static str?
    1. Do you only read text that something else owns, as in almost every parameter?

      Yes

      Borrow it: &strAccepts a &String, a literal and a slice of either, with no copy.

      No
    2. Is the text fixed when you compile, like a literal, a label or a message?

      Yes

      Use &'static strIt lives for the whole program, so you can return it or store it with no allocation.

      No
    3. Otherwise: You build, change or keep the text (a struct field, a value you return, text you push_str onto): own it with String

    Lists follow the same pattern: &[T] to read, Vec<T> to own, and [T; N] for a fixed number of items.

    WhatWhenWhyHow
    StringYou 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.
    &strYou 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 strText 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:

    String, &str and &String side by side
    String, &str and &String side by side: each row is one value; each cell's width is its size in bytes.
    Value01234567891011121314151617181920212223Size
    Stringptr8 bytes · pointerlen8 bytescapacity8 bytes24 bytes
    &strptr8 bytes · pointerlen8 bytes16 bytes
    &Stringptr8 bytes · pointer8 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}");
    After let word = &text[6..]On the stack, text is a String with a pointer to a heap buffer holding the 11 bytes h, e, l, l, o, a space, w, o, r, l, d, a length of 11 and a capacity of 11. Below it, word is a &str with a pointer to byte 6 of the same buffer, the w, and a length of 5. The slice has no capacity and owns nothing: it is a view into text's buffer.StackHeaptext: Stringptrlen11capacity11word: &strptrlen5heap bufferhello␣world
    After let word = &text[6..]. On the stack, text is a String with a pointer to a heap buffer holding the 11 bytes h, e, l, l, o, a space, w, o, r, l, d, a length of 11 and a capacity of 11. Below it, word is a &str with a pointer to byte 6 of the same buffer, the w, and a length of 5. The slice has no capacity and owns nothing: it is a view into text's buffer.

    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 here

    Finish 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.

    Starting code in TypeScript
    report.ts
    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));
    Starting code in C#
    Report.cs
    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.