Cannot pass references to functions and use them properly #16665
Unanswered
qwertfisch
asked this question in
Questions and Answers
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello!
I’m quite new to V and have a problem concerning iterating over a recursive list structure. That is, iterating works in the same function where the structure is defined, but I cannot create a mutable reference that just points to any inner list using a function.
Here is the definition of the structure and the working code:
The function in the for loop should iterate over the
ValueList, get the last element, and if it’s another list, recursively find the next last element of this list, and so on. It doesn’t matter exactly what it does. The point is, the referencelast_valueis updated, and in the last lines you can see, I add an element to the last list, and the complete list is also updated. Works as intended.But when I want to move the code into a function, the same thing works differently.
I still get a reference to the element I wanted to find, but it also changes the complete list. This can be seen with this added code to the main function:
Question
So the question is: How can I move the code from the main function into another function? How can I pass a mutable reference, and changing this reference only changes the reference and not the referenced value?
Another strange behaviour
Also, when testing around with other implementation variants, I discovered this very strange behaviour:
If I copy the reference (here the function parameter
list), I still get value type, not a reference! Why?And changing values based on the copied and/or returned reference would then only change a duplicate of the complete structure, and that is quite useless, because I passed a reference to just not create any duplicates.
Beta Was this translation helpful? Give feedback.
All reactions