Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Cool stuff, what's the significance of "!" as a return value? Haven't seen that one before.


It 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()
    };


Is ! verified or enforced; i.e. does the compiler check to make sure that the functions does terminate in some way (besides returning) ?


It'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.


Looks 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#intrin...


It seems to be equivalent to Haskell's Void type. The Void type is simply the type of no values. If you cannot create a value of this type, yet you "return" it, then it is proof that you never return.


Also "Nothing" in Scala and "never" in TypeScript. The bottom type[1] goes by a lot of names.

Interesting, I think Haskell does sort of have a value for it, undefined. It's just that if you look at that value too hard, it throws. :)

[1]: https://en.wikipedia.org/wiki/Bottom_type


It'd be type and memory unsafe if it weren't verified, so yes, it is.


Good to know, that explains why I've never seen it.


And an RFC for it to become its own type recently got approved: 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.



apparently it indicates divergence, i.e. the function does not return at all. Very interesting, I've never seen the notation before.



Swift 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)


_Noreturn is a standard keyword in C11. C++11 has a standard attribute called [[noreturn]].




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: