Rust puzzlers in quiz form


#1

@dtolnay put this together. Good collection of Rust puzzlers (I think that’s what I’d call most of them).


Tricky programs
#2

I don’t get #13’s explanation:

struct S;

fn main() {
    let [x, y] = &mut [S, S];
    let eq = x as *mut S == y as *mut S;
    print!("{}", eq as u8);
}

Explanation:

The first line of main creates a local value of type [S; 2] . Let’s refer to that temporary as tmp . The let -binding binds two references into tmp , x referring to &mut tmp[0] and y referring to &mut tmp[1] .

There’s no tmp here.


#3

This is referring to promoting an rvalue, to which a reference is taken, to having storage so that you can take a reference to it. In other words, it’s the same thing as:

let v = &mut Vec::new();

Compiler treats this as-if you wrote:

let mut tmp = Vec::new();
let v = &mut tmp;

The explanation is referring to the same type of thing, except replace Vec with [S; 2].


#4

Got it; thanks.