Random Rust quiz


#1

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?


#2

let foo = ();?


#3

Not exactly, here’s a counterexample:

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

#4
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?


#5

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:


#6

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…


#7

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