Hey, I am currently trying to achieve the following:
I have a Self which is just a Vec and it represents a square of pixels flattened to 1D. So to get pixel(x,y) I would return &self[x + width*y]. Now I want to get a specific subset of my square which is one of the 4 v-shaped parts enclosed by the two diagonals:
for this purpose I wrote the following method (because I wanted to have as few redundant code as possible):
fn get_quadrant(&self, quadrant: Quadrant) -> Vec<&T> {
let width = self.side_length();
let get_triangle = <some closure>;
let get_quadrant_like = <another closure>
match quadrant {
Quadrant::RightTriangularQuadrant => {
let columns = get_triangle(0, width);
let f: fn(usize) -> usize = |x: usize| width - 1 - x;
let g = |a: usize, b: usize| (a,b);
get_quadrant_like(f,g)
},
Quadrant::TopTriangularQuadrant => todo!(),
Quadrant::LeftTriangularQuadrant => todo!(),
Quadrant::BottomTriangularQuadrant => todo!(),
_ => todo!(),
}
}
Here are the two helper closures I use in more detail, first get_triangle:
let get_triangle = |mut start: usize, mut end: usize| {
let mut result = Vec::with_capacity(width/2);
while end - start > 0 {
let mut row = Vec::with_capacity(width/2);
for i in start..end {
row.push(i);
}
result.push(row);
start -= 1;
end -= 1;
}
result
};
and second get_quadrant_like
let get_quadrant_like =
|f: fn(usize) -> usize,
g: fn(usize, usize) -> (usize, usize)| {
let columns = get_triangle(start, width);
let mut result = Vec::with_capacity(self.len()/2);
for (i, column) in columns.iter().enumerate() {
let fixed = f(i);
for loose in column.iter() {
let (x, y) = g(fixed, *loose);
result.push(self.get(x, y));
}
}
result
};
The compiler complains in my match expression when I try to define the function f:
mismatched types
expected fn pointer fn(usize) -> usize
found closure {closure@src\evolution\gene.rs:119:45: 119:55}
and
closures can only be coerced to fn
types if they do not capture any variables
I also tried to redefine the fn() -> ... type to impl Fn() but this just created problems somewhere else. I am new to rust and have not used closures that often. Does someone maybe know where the problem might be?
Thank you very much!