4 ms·
Cool stuff, what's the significance of "!" as a return value? Haven't seen that one before.
by vvanders 10y ago
Cool stuff, what's the significance of "!" as a return value? Haven't seen that one before.
- webkike 10y agoapparently it indicates divergence, i.e. the function does not return at all. Very interesting, I've never seen the notation before.
- phil-opp 10y agoSee https://doc.rust-lang.org/book/functions.html#diverging-functions https://doc.rust-lang.org/book/functions.html#diverging-func... and https://doc.rust-lang.org/reference.html#diverging-functions https://doc.rust-lang.org/reference.html#diverging-functions
- Gankro 10y agoSwift encodes this with a noreturn attribute, and I think it's a "standard not standard" C attribute as well. (in case you were wondering who else does this)
- alexbock 10y ago_Noreturn is a standard keyword in C11. C++11 has a standard attribute called [[noreturn]].
- pcwalton 10y agoIt means that the function never returns (via exiting the process, exiting the thread, or by panicking). It's useful because the result of a function that returns ! is compatible with any type, so you can write things like: fn usage() -> ! { println!("usage: myapp FILENAME"); process::exit(0) } let filename = if args.len() < 2 { args[1].clone() } else { usage() };
- vvanders 10y agoGood to know, that explains why I've never seen it.
- swsieber 10y agoAnd an RFC for it to become its own type recently got approved: https://github.com/rust-lang/rfcs/pull/1216 https://github.com/rust-lang/rfcs/pull/1216 (The github thread also has a ton of good discussion about it. I learned a lot). Up until now it's been a big edge case. This makes it considerably smaller.
- winter_blue 10y agoIs ! verified or enforced; i.e. does the compiler check to make sure that the functions does terminate in some way (besides returning) ?
- jonesetc 10y agoLooks like it [0]. The author had to use inline assembly, so compiler couldn't enforce it and failed to compile. They had to add an annotation to say that the code after the assembly was unreachable. [0] http://os.phil-opp.com/better-exception-messages.html#intrinsics-unreachable http://os.phil-opp.com/better-exception-messages.html#intrin...
- Gankro 10y agoIt's the exact same analysis as ensuring all paths of a function do return the right type -- you just make sure all paths call a divergent function (typically unconditional panic) or enter a loop {} that never breaks/returns. This is of course a conservative analysis so e.g. "while true { }" is assumed to terminate and is rejected. Failing to perform this verification correctly would trivially lead to memory unsafety as calling code is allowed to assume such a function returns any and all requested types.
- pcwalton 10y agoIt'd be type and memory unsafe if it weren't verified, so yes, it is.
- frutiger 10y agoSee: https://en.wikipedia.org/wiki/Bottom_type https://en.wikipedia.org/wiki/Bottom_type