Rust Macro for multiple Results unwrap


#1

I Just started playing with the Macros, I’m not confident enough yet with it’s powers and syntax.
Would it be possible to create a super macro that supports this kind of thing?

let mut resp = try_do!{
    name    <- ss.read_line();               // we could also use the let binding
    ip_addr <- name.parse::<IPAddr>();
    conn    <- socket.connect(&ip_addr);
    conn.response()
}

so I could avoid the whole unwrap thing and chaining multiple try! instead?
What do you think about it? Is the idea to crazy?

cheers,
DL


#2

Im pretty sure this use case is what and_then is for

ss.read_line()
    .and_then(|name| name.parse::<IPAddr>())
    .and_then(|ip_addr| socket.connect(&ip_addr))
    .and_then(|conn| conn.response())

assuming all those methods return results or options, if they just return a value you can use map

links:


#3

Yes, here’s a do notation macro

Alternatively if this PR gets accepted (it needs an approved RFC first), then you could write ss.read_line()?.parse::<IPAddr>()?.connect()?.response() or something like that (see the test files in the PR).

See also this postponed RFC for more ideas on error handling syntatic sugar. (We may implement a fraction of that for 1.0)