I'm trying to implement A* search for Advent of Code 2019 (Yes, Slowpoke, I know). I've started like this:
fn find_path(start: Coords, goal: Coords, map: &Vec<Vec<char>>) -> Vec<Coords> {
struct Node {
distance: u32,
pos: Coords,
}
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.distance + manhattan(self.pos, goal) == other.distance + manhattan(other.pos, goal)
}
}
...
let mut edge = BinaryHeap::new();
edge.push(Node{distance: 0, pos: start});
...
Coords
is a struct with an x
and an y
. The problem here is that I can't use goal
in the trait, because it's not in scope. A closure would be able to capture it, but I am doubtful whether I can use a closure instead of a fn
here. If so, what's the syntax? If not, is there a fundamental reason why it can't be done? I wasn't able to find an answer online.
I know the simple solution is to include goal
in Node
, but it's redundant because I'll be creating thousands of Node
during A*, all of which will have the same goal, wasting memory and CPU cycles. In principle, goal
could be a single global variable, but that's an untidy option.
Even though I'm sure including goal
in Node
would work fine in practice, I'd rather not.
Is there another idiomatic way of accomplishing what I'm trying to do?