Flattening a nested structure












2















Looks for wisdom on fixing this borrow-checker/lifetime issue in Rust. I'm trying to flatten a generic nested structure (into an impl Iterator or Vec). It's perhaps a few &s and `s away from working:



fn iter_els(prev_result: Vec<&El>) -> Vec<&El> {
// Iterate over all elements from a tree, starting at the top-level element.
let mut result = prev_result.clone();

for el in prev_result {
for child in &el.children {
result.push(&child.clone());
}
result.extend(iter_els(&el.children));
}
result
}


You'll note that the immediate exception this raises is that iter_els expects a Vec of refs, not a ref itself. When addressing this directly, other issues rear their mischievous heads, as in a game of oxidized, but safe wack-a-mole.



Playground










share|improve this question



























    2















    Looks for wisdom on fixing this borrow-checker/lifetime issue in Rust. I'm trying to flatten a generic nested structure (into an impl Iterator or Vec). It's perhaps a few &s and `s away from working:



    fn iter_els(prev_result: Vec<&El>) -> Vec<&El> {
    // Iterate over all elements from a tree, starting at the top-level element.
    let mut result = prev_result.clone();

    for el in prev_result {
    for child in &el.children {
    result.push(&child.clone());
    }
    result.extend(iter_els(&el.children));
    }
    result
    }


    You'll note that the immediate exception this raises is that iter_els expects a Vec of refs, not a ref itself. When addressing this directly, other issues rear their mischievous heads, as in a game of oxidized, but safe wack-a-mole.



    Playground










    share|improve this question

























      2












      2








      2








      Looks for wisdom on fixing this borrow-checker/lifetime issue in Rust. I'm trying to flatten a generic nested structure (into an impl Iterator or Vec). It's perhaps a few &s and `s away from working:



      fn iter_els(prev_result: Vec<&El>) -> Vec<&El> {
      // Iterate over all elements from a tree, starting at the top-level element.
      let mut result = prev_result.clone();

      for el in prev_result {
      for child in &el.children {
      result.push(&child.clone());
      }
      result.extend(iter_els(&el.children));
      }
      result
      }


      You'll note that the immediate exception this raises is that iter_els expects a Vec of refs, not a ref itself. When addressing this directly, other issues rear their mischievous heads, as in a game of oxidized, but safe wack-a-mole.



      Playground










      share|improve this question














      Looks for wisdom on fixing this borrow-checker/lifetime issue in Rust. I'm trying to flatten a generic nested structure (into an impl Iterator or Vec). It's perhaps a few &s and `s away from working:



      fn iter_els(prev_result: Vec<&El>) -> Vec<&El> {
      // Iterate over all elements from a tree, starting at the top-level element.
      let mut result = prev_result.clone();

      for el in prev_result {
      for child in &el.children {
      result.push(&child.clone());
      }
      result.extend(iter_els(&el.children));
      }
      result
      }


      You'll note that the immediate exception this raises is that iter_els expects a Vec of refs, not a ref itself. When addressing this directly, other issues rear their mischievous heads, as in a game of oxidized, but safe wack-a-mole.



      Playground







      rust






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 13:20









      Turtles Are CuteTurtles Are Cute

      1,06851829




      1,06851829
























          1 Answer
          1






          active

          oldest

          votes


















          1














          There are various solutions to this task. One would be to pass the result as an out-parameter to the function:



          fn iter_els<'el>(el_top: &'el El, result: &mut Vec<&'el El>) {
          result.push(el_top);
          for el in &el_top.children {
          iter_els(el, result);
          }
          }

          fn main() {
          // build top_el as you did
          let mut result = Vec::new();
          iter_els(&top_el, &mut result);
          println!("{:?}", result);
          }


          Adapting your original approach imho results in a more complex implementation:



          fn iter_els<'el>(prev_result: &Vec<&'el El>) -> Vec<&'el El> {
          // Iterate over all elements from a tree, starting at the top-level element.
          let mut result = prev_result.clone();

          for el in prev_result {
          for child in &el.children {
          result.push(&child);
          }
          result.extend(iter_els(&el.children.iter().collect()));
          }
          result
          }

          fn main() {
          // build top_el as you did
          println!("{:?}", iter_els(&vec![&top_el]));
          }


          Alternatively:



          fn iter_els<'el>(prev_result: &'el Vec<El>) -> Vec<&'el El> {
          // Iterate over all elements from a tree, starting at the top-level element.
          let mut result : Vec<_> = prev_result.iter().collect();

          for el in prev_result {
          for child in &el.children {
          result.push(child);
          }
          result.extend(iter_els(&el.children));
          }
          result
          }

          fn main() {
          // build top_el as you did
          println!("{:?}", iter_els(&vec![top_el]));
          }


          As you can see, the first approach only operates on an immutable El, and one single result Vec, while the other implementations do not get around clone and collect.



          Ideally, you would write a custom Iterator for your tree, but I think this could get quite cumbersome, because this iterator would have to keep track of the current state somehow (maybe can prove me wrong and show that it's actually easy to do).






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53467880%2fflattening-a-nested-structure%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            There are various solutions to this task. One would be to pass the result as an out-parameter to the function:



            fn iter_els<'el>(el_top: &'el El, result: &mut Vec<&'el El>) {
            result.push(el_top);
            for el in &el_top.children {
            iter_els(el, result);
            }
            }

            fn main() {
            // build top_el as you did
            let mut result = Vec::new();
            iter_els(&top_el, &mut result);
            println!("{:?}", result);
            }


            Adapting your original approach imho results in a more complex implementation:



            fn iter_els<'el>(prev_result: &Vec<&'el El>) -> Vec<&'el El> {
            // Iterate over all elements from a tree, starting at the top-level element.
            let mut result = prev_result.clone();

            for el in prev_result {
            for child in &el.children {
            result.push(&child);
            }
            result.extend(iter_els(&el.children.iter().collect()));
            }
            result
            }

            fn main() {
            // build top_el as you did
            println!("{:?}", iter_els(&vec![&top_el]));
            }


            Alternatively:



            fn iter_els<'el>(prev_result: &'el Vec<El>) -> Vec<&'el El> {
            // Iterate over all elements from a tree, starting at the top-level element.
            let mut result : Vec<_> = prev_result.iter().collect();

            for el in prev_result {
            for child in &el.children {
            result.push(child);
            }
            result.extend(iter_els(&el.children));
            }
            result
            }

            fn main() {
            // build top_el as you did
            println!("{:?}", iter_els(&vec![top_el]));
            }


            As you can see, the first approach only operates on an immutable El, and one single result Vec, while the other implementations do not get around clone and collect.



            Ideally, you would write a custom Iterator for your tree, but I think this could get quite cumbersome, because this iterator would have to keep track of the current state somehow (maybe can prove me wrong and show that it's actually easy to do).






            share|improve this answer






























              1














              There are various solutions to this task. One would be to pass the result as an out-parameter to the function:



              fn iter_els<'el>(el_top: &'el El, result: &mut Vec<&'el El>) {
              result.push(el_top);
              for el in &el_top.children {
              iter_els(el, result);
              }
              }

              fn main() {
              // build top_el as you did
              let mut result = Vec::new();
              iter_els(&top_el, &mut result);
              println!("{:?}", result);
              }


              Adapting your original approach imho results in a more complex implementation:



              fn iter_els<'el>(prev_result: &Vec<&'el El>) -> Vec<&'el El> {
              // Iterate over all elements from a tree, starting at the top-level element.
              let mut result = prev_result.clone();

              for el in prev_result {
              for child in &el.children {
              result.push(&child);
              }
              result.extend(iter_els(&el.children.iter().collect()));
              }
              result
              }

              fn main() {
              // build top_el as you did
              println!("{:?}", iter_els(&vec![&top_el]));
              }


              Alternatively:



              fn iter_els<'el>(prev_result: &'el Vec<El>) -> Vec<&'el El> {
              // Iterate over all elements from a tree, starting at the top-level element.
              let mut result : Vec<_> = prev_result.iter().collect();

              for el in prev_result {
              for child in &el.children {
              result.push(child);
              }
              result.extend(iter_els(&el.children));
              }
              result
              }

              fn main() {
              // build top_el as you did
              println!("{:?}", iter_els(&vec![top_el]));
              }


              As you can see, the first approach only operates on an immutable El, and one single result Vec, while the other implementations do not get around clone and collect.



              Ideally, you would write a custom Iterator for your tree, but I think this could get quite cumbersome, because this iterator would have to keep track of the current state somehow (maybe can prove me wrong and show that it's actually easy to do).






              share|improve this answer




























                1












                1








                1







                There are various solutions to this task. One would be to pass the result as an out-parameter to the function:



                fn iter_els<'el>(el_top: &'el El, result: &mut Vec<&'el El>) {
                result.push(el_top);
                for el in &el_top.children {
                iter_els(el, result);
                }
                }

                fn main() {
                // build top_el as you did
                let mut result = Vec::new();
                iter_els(&top_el, &mut result);
                println!("{:?}", result);
                }


                Adapting your original approach imho results in a more complex implementation:



                fn iter_els<'el>(prev_result: &Vec<&'el El>) -> Vec<&'el El> {
                // Iterate over all elements from a tree, starting at the top-level element.
                let mut result = prev_result.clone();

                for el in prev_result {
                for child in &el.children {
                result.push(&child);
                }
                result.extend(iter_els(&el.children.iter().collect()));
                }
                result
                }

                fn main() {
                // build top_el as you did
                println!("{:?}", iter_els(&vec![&top_el]));
                }


                Alternatively:



                fn iter_els<'el>(prev_result: &'el Vec<El>) -> Vec<&'el El> {
                // Iterate over all elements from a tree, starting at the top-level element.
                let mut result : Vec<_> = prev_result.iter().collect();

                for el in prev_result {
                for child in &el.children {
                result.push(child);
                }
                result.extend(iter_els(&el.children));
                }
                result
                }

                fn main() {
                // build top_el as you did
                println!("{:?}", iter_els(&vec![top_el]));
                }


                As you can see, the first approach only operates on an immutable El, and one single result Vec, while the other implementations do not get around clone and collect.



                Ideally, you would write a custom Iterator for your tree, but I think this could get quite cumbersome, because this iterator would have to keep track of the current state somehow (maybe can prove me wrong and show that it's actually easy to do).






                share|improve this answer















                There are various solutions to this task. One would be to pass the result as an out-parameter to the function:



                fn iter_els<'el>(el_top: &'el El, result: &mut Vec<&'el El>) {
                result.push(el_top);
                for el in &el_top.children {
                iter_els(el, result);
                }
                }

                fn main() {
                // build top_el as you did
                let mut result = Vec::new();
                iter_els(&top_el, &mut result);
                println!("{:?}", result);
                }


                Adapting your original approach imho results in a more complex implementation:



                fn iter_els<'el>(prev_result: &Vec<&'el El>) -> Vec<&'el El> {
                // Iterate over all elements from a tree, starting at the top-level element.
                let mut result = prev_result.clone();

                for el in prev_result {
                for child in &el.children {
                result.push(&child);
                }
                result.extend(iter_els(&el.children.iter().collect()));
                }
                result
                }

                fn main() {
                // build top_el as you did
                println!("{:?}", iter_els(&vec![&top_el]));
                }


                Alternatively:



                fn iter_els<'el>(prev_result: &'el Vec<El>) -> Vec<&'el El> {
                // Iterate over all elements from a tree, starting at the top-level element.
                let mut result : Vec<_> = prev_result.iter().collect();

                for el in prev_result {
                for child in &el.children {
                result.push(child);
                }
                result.extend(iter_els(&el.children));
                }
                result
                }

                fn main() {
                // build top_el as you did
                println!("{:?}", iter_els(&vec![top_el]));
                }


                As you can see, the first approach only operates on an immutable El, and one single result Vec, while the other implementations do not get around clone and collect.



                Ideally, you would write a custom Iterator for your tree, but I think this could get quite cumbersome, because this iterator would have to keep track of the current state somehow (maybe can prove me wrong and show that it's actually easy to do).







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 25 '18 at 13:57

























                answered Nov 25 '18 at 13:39









                phimuemuephimuemue

                20.6k66298




                20.6k66298
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53467880%2fflattening-a-nested-structure%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python