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
}
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
}
}
The borrow checker allows returning &TRUE
and &true
because those expressions produce references with 'static
lifetime. Such references can be coerced to references of any other lifetime, including the lifetime of &self
as required by the signature of Index::index()
.