Beginner question


#1

Hi, I’m new to Rust and was wondering if it is possible to return b without having to explicitly write it at the end?

pub fn new(rows : usize, cols : usize) -> Board {
    let mut b = Board {
        rows,
        cols,
        size : rows * cols,
        tiles : Vec::new(),
    };
    b.init();
    b.shuffle();
    b
}

Thanks in advance! :slight_smile:


#2

If you weren’t calling methods on b, you could do this:

pub fn new(rows : usize, cols : usize) -> Board {
    Board {
        rows,
        cols,
        size: rows * cols,
        tiles: Vec::new(),
    } // note the lack of semicolon
}

But if you want to call methods on b before returning, then no, you’ll need to put it at the end.


#3

Alright, thanks for your fast reply! :slight_smile:


#4

If init and shuffle were defined as:

fn init(self) -> Self { ... }
fn shuffle(self) -> Self { ... }

Then you can do:

pub fn new(rows : usize, cols : usize) -> Board {
    Board {
        rows,
        cols,
        size: rows * cols,
        tiles: Vec::new(),
    }.init().shuffle()
}

But what you have is fine and normal, IMO.


#5

Ah cool, that looks a bit cleaner imho. Will try it out, thanks!