0Pricing
Learn Rust Coding · Aula

String versus &str

Propriedade do texto

String versus &str é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Owned vs Borrowed Text

Rust separates text ownership into two types:

  • String — owns its data on the heap.
  • &str — borrows a view of text it does not own.
fn main() {
    let owned = String::from("I own this");
    let borrowed: &str = "I am borrowed";
    println!("{} / {}", owned, borrowed);
}

Where the Data Lives

A String stores its bytes on the heap and can grow. A string literal &str is baked into the program binary and is fixed.

fn main() {
    let mut heap = String::from("grows");
    heap.push_str(" bigger");
    let fixed = "never changes";
    println!("{} | {}", heap, fixed);
}

Ownership Means Responsibility

The owner of a String frees its memory when it goes out of scope. A &str owns nothing, so it never frees anything.

fn main() {
    {
        let s = String::from("temporary");
        println!("{}", s);
    } // s is dropped and its memory freed here
    println!("done");
}

Borrowing a String

You can borrow a String as a &str using &. The String still owns the data; the slice just looks at it.

fn main() {
    let owned = String::from("shared text");
    let view: &str = &owned;
    println!("{} / {}", owned, view);
}

Moving a String

Assigning a String to another variable moves ownership. The original can no longer be used.

fn main() {
    let a = String::from("hello");
    let b = a; // ownership moves to b
    // println!("{}", a); // would error: a was moved
    println!("{}", b);
}

Cloning to Keep Both

If you need two independent owned strings, use clone to copy the data.

fn main() {
    let a = String::from("hello");
    let b = a.clone();
    println!("{} and {}", a, b);
}

Copying a &str Is Cheap

A &str is just a pointer and length, so copying it does not copy the underlying text. It implements Copy.

fn main() {
    let original = "data";
    let copy = original; // both still valid
    println!("{} {}", original, copy);
}

Functions and Ownership

Passing a String by value moves it into the function. Passing &str or &String only borrows, leaving the caller's value usable.

fn length(s: &str) -> usize {
    s.len()
}

fn main() {
    let text = String::from("measure me");
    println!("{}", length(&text));
    println!("still here: {}", text);
}

Returning Owned Strings

When a function must produce new text, it returns an owned String so the caller takes ownership.

fn make_greeting(name: &str) -> String {
    format!("Hello, {}!", name)
}

fn main() {
    let g = make_greeting("Rust");
    println!("{}", g);
}

Choosing the Right Type

Guidelines:

  • Store owned text? Use String.
  • Just read or pass text? Accept &str.
  • Build new text in a function? Return String.
fn first_word(s: &str) -> &str {
    s.split_whitespace().next().unwrap_or("")
}

fn main() {
    let sentence = String::from("learn rust today");
    println!("{}", first_word(&sentence));
}

Why the Distinction Matters

This split lets Rust avoid unnecessary copies and guarantees memory safety without a garbage collector. You always know who owns a piece of text.

fn main() {
    let owned = String::from("safe");
    let borrowed = &owned[..];
    println!("owner {} borrows {}", owned, borrowed);
}

Quick Check

Recall what happens when you move a String.

Recap

String vs &str ownership:

  • String owns heap data and frees it on drop.
  • &str borrows existing text and owns nothing.
  • Moving a String invalidates the original; clone copies it.
  • Accept &str to read, return String to produce new text.
fn shout(s: &str) -> String {
    s.to_uppercase()
}

fn main() {
    let name = String::from("rust");
    let loud = shout(&name);
    println!("{} -> {}", name, loud);
}

Perguntas Frequentes

A aula “String versus &str” é grátis?

Sim — o texto completo de “String versus &str” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.

O que vou aprender em “String versus &str”?

Propriedade do texto Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Learn Rust Coding?

Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “String versus &str”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Learn Rust Coding?

Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. String versus &str
  2. Fatias
  3. Métodos de String
  4. UTF-8 e caracteres
← Voltar para Learn Rust Coding