Now let's talk about what the `let`, `var`, `=` means semantically for ref
type, when it is clear, then the programmer know what he is doing exactly, and
the compiler know what the programmer doing wrong. (We talk about the parameter
and return value later)
For value object type, they are clear basicly:
1. `let` means readonly binding, you cannot change the value and the variable
binding(change the variable binding means change value too).
2. `var` means mutable binding, you can change the value and the variable
binding.
3. `=` for `let` variable means shallow copy.
4. `=` for `var` variable means copy(not deep copy if I don't make mistake).
Now for ref type, what should be with `let`, `var` and `=` ?, For ref type,
variable is bound to the pointer of the value, not the value self. Let's try
simulate the semantic of the value object type.
1. `let` means readonly binding, you cannot change the value and the variable
binding.
2. `var` means mutable binding, you can change the value and the variable
binding.
3. `=` assign `let` variable to `let` variable, pointer copy, it's fine.
4. `=` assign `var` variable to `let` variable, pointer copy, it's fine.
5. `=` assign `var` variable to `var` variable, pointer copy, it's fine.
6. `=` assign `let` variable to `var` variable, ??? what should it be?
pointer copy? value copy?
Here is code to show the problem:
type
Node = ref object
left, right: Node
proc f1() =
let n = Node()
var v = n # ??? pointer copy? value copy?
v.left = Node() # ??? semanticly error or it is the real meaning of
the programmer
proc f2() =
var v = Node()
let n = Node()
v.left = n # ???
v.left.left = Node() # ??? semanticly error or it is the real meaning of
the programmer
Run
When assign `let` variable to `var` variable allowed, the compiler don't know
what is the real meaning of the programmer, it is a error or the programmer
wish make a copy of node(just like the value object). It is not about something
optimize code, it is about what the programmer want to do.
By the way, for graph traverse, we can use iterator or just something like
`mut` variable, which we can change the variable binding but cannot change the
value.