Ownership and Borrowing
Ownership, moves, and borrowing - the core of Rust memory safety. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Busca en todas las páginas de la documentación
Ownership, moves, and borrowing - the core of Rust memory safety. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Assigning a non-Copy value moves it; the old name is invalid.
let s = String::from("hi");
let t = s;
// s is moved; use t
t // "hi"Many shared references &T are allowed at once.
let s = String::from("hi");
let r1 = &s;
let r2 = &s;
r1.len() + r2.len() // 4Only one &mut T at a time; no shared refs while it lives.
let mut s = String::from("hi");
{
let r = &mut s;
r.push('!');
}
s // "hi!"Copy types duplicate on assign; others need .clone() for a deep-ish copy.
let a = 5;
let b = a; // Copy
a + b // 10
let s = String::from("x");
let t = s.clone();
t // "x"Slices are fat pointers into owned data without taking ownership.
let v = vec![1, 2, 3];
let s = &v[1..];
s // [2, 3]Passing a non-Copy value moves into the function unless you borrow.
fn len(s: String) -> usize { s.len() }
len(String::from("ab")) // 2Prefer &T / &mut T parameters so callers keep ownership.
fn len(s: &str) -> usize { s.len() }
len("ab") // 2Return owned values to hand data back to the caller.
fn make() -> String {
String::from("ok")
}
make() // "ok"Borrows end at last use (NLL), not always at block braces.
let mut x = 1;
let r = &x;
let y = *r;
x += 1; // ok after last use of r
x + y // 3&String coerces to &str at call sites.
fn chars(s: &str) -> usize { s.chars().count() }
let owned = String::from("hi");
chars(&owned) // 2Moving one field can partially move a struct - reassemble carefully.
struct P { a: String, b: i32 }
let p = P { a: "x".into(), b: 1 };
let a = p.a;
// p.a moved; p.b still usable
p.b // 1Borrow inside patterns with ref / ref mut.
let s = Some(String::from("hi"));
match s {
Some(ref v) => v.len(), // 2
None => 0,
}String literals are 'static - live for the whole program.
let s: &'static str = "hello";
s // "hello"Simple input/output lifetime links are inferred on functions.
fn first(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
first("a b") // "a"Annotate when elision cannot decide the relationship.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
longest("ab", "z") // "ab"Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Revisado por Chris St. John·Última actualización: 19 jul 2026