I'm trying to make a callback as a parameter, and make it Option
-al. I'm probably abusing the syntax or misunderstanding the type of do_skip_node
, but is it possible to make such a function with a default fallback?
struct Node {}
struct MyParser {
skip_nodes: bool
}
fn do_skip_node(n: Node) {}
impl MyParser {
// this compiles
fn works<NC>(&mut self, node_cb: NC) where NC: Fn(Node) {}
// this does not compile
fn fails<NC>(&mut self, node_cb: Option<NC>)
where NC: Fn(Node)
{
let ncb = if let Some(n) = node_cb {
self.skip_nodes = false;
n
} else {
self.skip_nodes = true;
do_skip_node // or |n: Node| {}
};
}
}
Here's the error message. Do I understand it correctly that the upper part of the if
returns a type, not the actual fn instance?
11 | fn fails<NC>(&mut self, node_cb: Option<NC>)
| -- this type parameter
...
14 | let ncb = if let Some(n) = node_cb {
| ___________________-
15 | | self.skip_nodes = false;
16 | | n
| | - expected because of this
17 | | } else {
18 | | self.skip_nodes = true;
19 | | do_skip_node // or |n: Node| {}
| | ^^^^^^^^^^^^ expected type parameter `NC`, found fn item
20 | | };
| |_________- `if` and `else` have incompatible types
|
= note: expected type `NC`
found fn item `fn(Node) {do_skip_node}`