This variable is not stubborn. You misunderstood/didnt notice that struct
s are special.
Structs are handled by value, not by reference.
When you write:
foo.mystructList[5]
you are referring to an item of an List. But since that List does not hold objects - this indexing returns you a copy.
Consider this:
var temp = foo.mystructList[5]
temp.flip()
would you now expect the 'flip()' to work? remember that the List holds structs. Surely, you wouldn't consider it to work, since you are flipping a copy.
Now back to your case:
foo.mystructList[5].flip()
that's the same as above! I just eliminated the temporary variable, but inside, that's the same. List is read, copy is returned, the flip is called on the copy.
Here:
foo.mystructList[5].prop = true
the compiler rejects that 'lefthand is not a variable', because it knows that the lefthand is 'a copy' that will evaporate soon.
Here:
foo.mystructList[5].flip()
compiler cannot warn you: you are calling a method on a copy. What happens, is up to the method - if it plays along with structs well, it will work. Example:
var area = foo.rectangles[5].calculatearea(); // =x*y, OK!
foo.rectangles[5].validate(); // throw when x<0 || y<0, OK!
foo.rectangles[5].draw(); // call some UI rendere with x,y,sizeX,sizeY, OK!
..but if it tries to alter the struct, it will still succeed, but on the copy. There's no warning, since it's correct in all cases - just suprising when seen for the first time.
For a fun example, consider 'chaining':
struct Rect {
....
public Rect twiceMe() {
this.SizeX *= 2;
this.SizeY *= 2;
return this;
}
}
foo.rectangles[5].twiceMe().draw();
Here, twiceMe() returns altered this
, so I can "immediatelly" call draw
on it. It seems as if I multiplied the rectangle by two on the fly, and then drawn it on screen with twice the size, but there will be no changes in the array!
Works, but, actually, none of those calls were really immediate. The above example works like:
- read sixth item from the array, return the item (automatic copy here)
- call twiceMe() on that copy, return "this" from it (automatic copy here, too)
- call draw on copy-of-enlargedcopy-of-original
To sum up: don't overuse structs, or know them well, add extra care when you are mutating them.