Getters Return Borrowed Field Views

Expose borrowed views from struct methods: &self to &str and &[u32] tie to self by elision, while an owned getter clones only when callers must escape.

RustData Integrity

Code

rustsnippet
37 lines
struct Player {
    name: String,
    scores: Vec<u32>,
}

impl Player {
    fn new(name: &str, scores: Vec<u32>) -> Self {
        Self { name: name.to_string(), scores }
    }

    // 生命周期省略:&self -> &str 等价于 &'a self -> &'a str,
    // 返回值的存活期与 self 的借用绑定
    fn name(&self) -> &str {
        &self.name
    }

    // 借用切片视图:调用方只读,不复制 Vec
    fn scores(&self) -> &[u32] {
        &self.scores
    }

    fn best(&self) -> Option<u32> {
        self.scores.iter().copied().max()
    }

    // 需要脱离 self 存活时才显式给 owned
    fn name_owned(&self) -> String {
        self.name.clone()
    }
}

fn main() {
    let p = Player::new("ada", vec![90, 75, 98]);
    println!("{} best {} of {:?}", p.name(), p.best(), p.scores());
    let owned = p.name_owned();
    println!("owned name: {owned}");
}

How the snippet works

One way to read it: the functions new, name, scores and best, doing all the work.

Using it

The main signature reads fn new(name: &str, scores: Vec<u32>) -> Self

The demo output is labeled (owned name:), so every printed line maps back to its originating operation.

There are 4 calls inside main — new, name, best and scores — executed top to bottom.

Key statements

fn new(name: &str, scores: Vec<u32>) -> Self {
Self { name: name.to_string(), scores }
}
fn name_owned(&self) -> String {
self.name.clone()
}
fn best(&self) -> Option<u32> {
self.scores.iter().copied().max()
}

Interactive Tools for This Topic

FAQ

What does Getters Return Borrowed Field Views print when run?
The script runs standalone; its 1 labeled outputs include `owned name:`.