String vs. &str
Besitz von Text
String vs. &str ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Learn Rust Coding-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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:
Stringowns heap data and frees it on drop.&strborrows existing text and owns nothing.- Moving a String invalidates the original;
clonecopies it. - Accept
&strto read, returnStringto 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);
}Häufig gestellte Fragen
Ist die Lektion „String vs. &str“ kostenlos?
Ja — der vollständige Text von „String vs. &str“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Learn Rust Coding-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „String vs. &str“?
Besitz von Text Du übst Learn Rust Coding mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Learn Rust Coding zu starten?
Keine Vorkenntnisse erforderlich. Learn Rust Coding auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „String vs. &str“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Learn Rust Coding-Lektion Code schreiben und ausführen?
Ja. Jede Learn Rust Coding-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- String vs. &str
- Slices
- String-Methoden
- UTF-8 und Chars