Denoting the type with using an intermediate variable

I have a struct 'self' with the following field

nodes: Vec<Option<Box<AlgorithmNode>>>,

Now I want to do something like this

let mut test_function = |w_index| {
    let w = self.nodes[w_index].as_ref();
    //...
};

This gives the error type annotations needed cannot infer type I don't really understand why it can't infer the type but I assume it's because of the closure or something.

So then I tried

let mut test_function = |w_index| {
    let w: Option<Box<AlgorithmNode>> = self.nodes[w_index];
    let w = w.as_ref();
    //...
};

But this also doesn't work because AlgorithmNode doesn't implement copy...

So I was wondering if there is some way to cast the self.nodes[w_index] without moving it into a variable. Something like

let mut test_function = |w_index| {
    let w = (Option<Box<AlgorithmNode>>)(self.nodes[w_index]).as_ref();
    //...
};

But I don't seem to find the correct syntax to do this. Any advice ?

Please show the whole error. I suspect it's referring to w_index.

2 Likes

It doesn't know if you want to index by usize or some sort of Range, etc.

-        let mut test_function = |w_index| {
+        let mut test_function = |w_index: usize| {
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.