error must-close
What it means#
A type marked @must_close has an asynchronous cleanup method (by default close, or @must_close(by: name)). If a value of that type can leave scope without calling that move method and without transferring ownership, the compiler rejects the program (§4.3). The synchronous Drop is only a safety net.
Example#
@must_close
data Conn { id: i32 }
impl Conn {
static fn dial(addr: str) -> Conn | NetError net => Conn{ id: 1 }
fn send(msg: str) -> () | NetError net { }
move fn close() -> () | NetError net { }
}
fn talk(addr: str) -> () | NetError net {
let c = Conn.dial(addr)? // <- must-close
c.send("hello")?
}error
must-close
How to fix#
@must_close
data Conn { id: i32 }
impl Conn {
static fn dial(addr: str) -> Conn | NetError net => Conn{ id: 1 }
fn send(msg: str) -> () | NetError net { }
move fn close() -> () | NetError net { }
}
fn talk(addr: str) -> () | NetError net {
let c = Conn.dial(addr)?
defer c.close()?
c.send("hello")?
}Close the value on every path, most simply with defer c.close()? right after creating it, or move it to an owner that will close it.