Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return &bool from function

I was working on a bitboard implementation and was trying to implement the index trait but couldn’t return value &bool because this creates a temp value which could not be returned. Is there any way I could return a &bool in another way?

use std::ops::Index;

pub struct Bitboard(usize);

impl Index<usize> for Bitboard {
    type Output = bool;

    fn index(&self, index: usize) -> &Self::Output {
        &(self.0 & (1 << index) != 0)
    }
}

fn main() {
    let board = Bitboard(0b000_000_000);
    // bit:                          ^
    println!("{}", board[0]);
    // false
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way I could return a &bool in another way?

For arbitrary types returning a reference to a generated value would not be possible without leaking memory. But since there are only two distinct bool values, you could create them as static variables and return references to those:

static TRUE: bool = true;
static FALSE: bool = false;
// return &TRUE and &FALSE from index()

But it gets even easier because Rust treats a simple &true and &false as if you did just that, so this compiles:

fn index(&self, index: usize) -> &bool {
    if self.0 & (1 << index) != 0 {
        &true
    } else {
        &false
    }
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading