Well the title says it all, but I'm just going to add my code as that makes it clearer what I want to do.
I have the following function:
fn calculate_rook_attacks_for(pos: &impl BoardPos, blockers: u64) -> u64 {
unimplemented!()
}
I now want a higher order function that takes such calculation functions (not just this one, all functions that have this signature), but I'm struggling on the type definition. Mostly with the trait part.
I've tried:
fn generate_all_possible_attacks_for(
calculate_moves_for: fn(impl BoardPos) -> u64
) {
// cool generations stuff
}
But apparently that's not allowed:
impl Traitonly allowed in function and inherent method return types, not infn.
I've also tried:
fn generate_all_possible_attacks_for<T>(
calculate_attacks_for: fn(&T, u64) -> u64,
)
where
T: BoardPos
{
// cool generation stuff
}
But that complains something about type inference when trying to call it:
cannot infer type for type parameter
Tdeclared on the functiongenerate_all_possible_attacks_for
If I try to add the type: ::<&impl BoardPos>, I'm back the the previous error.
I've tried various other things (also stuff with &dyn), but I can't remember them all.
I'm sure the resources on how to do this are out there, I just lack the correct terminology to look it up.
(Btw, I don't want to use &dyn in the actual function call, as I've heard that results in a runtime performance impact)
Edit
Upon reading the answer I realized I'd have to specify the type at some point. I'm not sure what to do in the following case though:
fn generate_magic_number_for(pos: &impl BoardPos, piece: Piece) -> u64 {
let idx = pos.idx();
let (relevant_moves, number_of_relevant_moves, get_attacks_for): (
u64,
u64,
fn(&impl BoardPos, u64) -> u64,
) = match piece {
Piece::Bishop => (
RELEVANT_BISHOP_MOVES_PER_SQUARE[idx],
NUMBER_OF_RELEVANT_BISHOP_MOVES_PER_SQUARE[idx],
piece::calculate_bishop_attacks_for,
),
Piece::Rook => (
RELEVANT_ROOK_MOVES_PER_SQUARE[idx],
NUMBER_OF_RELEVANT_ROOK_MOVES_PER_SQUARE[idx],
piece::calculate_rook_attacks_for,
),
_ => panic!(
"this function is only callable for bishops and rooks, was called with '{:?}'",
piece
),
};
/// ...
}