Random Rust quiz

Found yet another amusing piece of Rust grammar, and I can't resist sharing it! :slight_smile:

Consider the following fragment of rust code: {foo}(). What definition of foo would make this code compile?

4 Likes

let foo = ();?

1 Like

Not exactly, here's a counterexample:

fn main() {
    let foo = ();
    let _ = {foo}();
}
let foo = main;

Doesn't need to actually finish cleanly, right :stuck_out_tongue:?

Although that doesn't compile with

fn main() {
    let foo = main;
    {foo}()
}

which

let foo = ();

does.... are you implying there is something that works for both?

1 Like

does.... are you implying there is something that works for both?

No, I don't think there's something workable in both contexts. Perhaps extending stdlib and implementing Fn for ()?

But it is surprising that the code is parsed differently depending on context (as a call expression, or as two separate statements) :slight_smile:

And it's not entirely obvious (at least to me) which way the code will be parsed by looking at the context:

fn bar(_:()) {}

fn main() {
    let foo = &||{};
    let _ = {foo}();
    bar({foo}());
    () == {foo}();

    let foo = ();
    {foo}() == ();
    {foo}();
    {foo}()
}

Especially that LHS or RHS of an expression is parsed differently....

Looks like fn foo() {} does the trick.