Owning Methods Consume Self With into_parts

An into_parts method takes self by value and returns its fields, so calling it moves the struct away and any later use becomes a compile error.

RustData Integrity

Code

rustsnippet
36 lines
// 消费 self 的方法把字段值逐一交还调用方:
// 调用后结构体被移动,不能再使用,这正是所有权语义
struct Sample {
    label: String,
    value: u32,
}

impl Sample {
    fn new(label: &str, value: u32) -> Self {
        Self { label: label.to_string(), value }
    }

    // &self 借读:不消耗数据
    fn is_high(&self) -> bool {
        self.value > 50
    }

    // 惯用命名 into_*:拿走所有权并拆解为各字段
    fn into_parts(self) -> (String, u32) {
        (self.label, self.value)
    }
}

fn main() {
    let sample = Sample::new("cpu", 64);
    println!("high load: {}", sample.is_high());

    let (label, value) = sample.into_parts(); // sample 在这里被移动
    println!("parts: {label}={value}");

    // sample.into_parts(); // 取消注释就是编译错误:sample 已被移动
    // println!("{}", sample.label);

    let parts = Sample::new("mem", 42).into_parts(); // 临时值同样可以直接消费
    println!("temporary parts: {parts:?}");
}

How it works

The snippet is organized around the functions new, is_high, into_parts and main.

What to watch for

  • Nothing needs adding to the project before it runs.

Applying it

Entry signature: fn new(label: &str, value: u32) -> Self

Look for the high load:, parts:, temporary parts: prefixes as the file executes; they connect every printed line to the step behind it.

The demo flow inside main is new, is_high and into_parts — run the file to see it end to end.

Statements that carry the weight

fn new(label: &str, value: u32) -> Self {
    Self { label: label.to_string(), value }
}
fn into_parts(self) -> (String, u32) {
    (self.label, self.value)
}
fn is_high(&self) -> bool {
    self.value > 50
}

Interactive Tools for This Topic

FAQ

What does Owning Methods Consume Self With into_parts print when run?
Invoke the file as-is — the `high load:`, `parts:`, `temporary parts:` prefixes identify which step printed each line.