Skip to content

match on a field's Option payload binds a copy; a mutating call on the binding is silently lost #2541

Closed

Description

@ehartford

Probe (v0.15.3.0-g8182ccfb1, also on the listiter-view stack):

type Holder { current: Option[List[i32]] }
impl Holder:
    mut fn bump():
        match self.current:
            Some(c) => c.push(9)
            None => ()
fn main:
    var h = Holder { current: Some([1]) }
    h.bump()
    h.bump()
    match h.current:
        Some(c) => print(f"{c.len()}")
        None => print("none")

Prints 1 (--debug-alloc: leak count=0). The two pushes went to a copy of the list (D120 copy-on-write makes the copy cheap and the write private) and were lost. A person reading match self.current: Some(c) => c.push(9) inside a mut fn expects the field's list to grow, or a diagnostic. Nothing says a second value was made (§2.3: the compiler never produces a second live value from one unless the type is Copy); here one was, silently.

Expected: a match on a place projects its bindings as views of that place (D22: patterns are transparent to origins; D27: a binding names what is there), so c names the payload in place and c.push(9) is an in-place mutation through a mut self receiver, or is refused when the subject place is not mutable. Either way, never a copy whose writes vanish.

Found writing std's FlatMapped.next (the same pattern over current: Option[C] looped forever: c.next() advanced a copy, and freed it every turn). std is being rewritten with explicit ownership (pop() / push on a one-element List) until this is fixed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions