0Pricing
Learn Rust Coding · Lección

String frente a &str

Propiedad del texto

String frente a &str es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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);
}

Preguntas frecuentes

¿La lección «String frente a &str» es gratis?

Sí — el texto completo de «String frente a &str» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 4 lecciones en total.

¿Qué aprenderé en «String frente a &str»?

Propiedad del texto Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «String frente a &str»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. String frente a &str
  2. Slices
  3. Métodos de String
  4. UTF-8 y Chars
← Volver a Learn Rust Coding