#How would you write this?

5 messages · Page 1 of 1 (latest)

solemn bridge
#
pub fn global_cell_pos(&self, m: u16, n: u16) -> Option<Vector2<u16>> {
    let cell_pos = self.cell_pos(m, n);

    Some(
        cell_pos?
            + match self.global_bounds.position().try_into_other() {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("{}", e);
                    return None;
                }
            },
    )
}
#

This is definitely cleaner:

pub fn global_cell_pos(&self, m: u16, n: u16) -> Option<Vector2<u16>> {
    let cell_pos = self.cell_pos(m, n);
    let grid_global_pos = match self.global_bounds.position().try_into_other() {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{}", e);
            return None;
        }
    };

    Some(cell_pos? + grid_global_pos)
}
#

I'm happy with the second.

void gale
#
    pub fn global_cell_pos(&self, m: u16, n: u16) -> Option<Vector2<u16>> {
        let cell_pos = self.cell_pos(m, n)?;
        let grid_global_pos = self
            .global_bounds
            .position()
            .try_into_other()
            .map_err(|e| eprintln!("{}", e))
            .ok()?;

        Some(cell_pos + grid_global_pos)
    }
#

If you put the ? in the last line for cell_pos, it does unnecessary work getting grid_global_pos first, rather than returning None as soon as possible.