Is there a way to reflect changes to a variable in the reference?
Here's a small reproducible example:
This outputs:
When I want it to output
My logic was that because
q1
is a reference to mylist.list
, whenever I change mylist.list
, it should also be reflected in q1
. But it seems q1
is copying the value instead of taking a reference? Am I misunderstanding how references work as a whole?26 Replies
I think you've managed to find a language bug. Unless I'm missing something, this shouldn't compile at all. The "spooky action at a distance" definitely isn't allowed, but you are mutating the list while holding an immutable reference to it, so it should error.
😨
Welcome to pre-1.0 languages.
Borrow checkers are compilicated and we will see bugs for a while.
I see, should I file an issue?
Please file a bug.
👌
Note that
q1
should be an immutable reference, and that mylist.do_stuff(0)
manipulates the same origin.Mhm mhm
Congrats @Deftioon, you just advanced to level 3!
also, i tried
should
q1 = 1
be allowed or is it reassigning the variableq1 = 1
should be denied because that should be an immutable reference.Alright, thanks for the help. Would you happen to know how I could achieve the desired behaviour?
The desired behavior violates
mutable xor alias
, so UnsafePointer
if you really, really need to do it.Ah, okay. Thanks
This is the trade-off of the borrow checker. It stops you from doing things like this, but it also stops fun bugs like invalidated references due to an append.
:D makes a lot of sense
I thought this is intended behaviour for register passable types. Since they are always passed by copy and not by reference,
q1
is not a reference to anything but a simple copy. If it were a reference, you'd need to dereference it first, and the issue Owen pointed out would occur.
I may be wrong w.r.t. trivial types; after trying it out I think this also happens at other types. But I am sure that q1 = mylist[0]
creates a copy.
I'd need to go dig up some old discord threads, but I think you are still able to have a reference to a register passable type and the compiler needs to make it look like you're using a pointer even if you aren't.
This may be true (and would be useful in some instances). But I think that after the old references were renamed to Pointer, references behave in a way that they cannot be stored in a variable.
You can still have a reference stored in a variable, otherwise a lot of stuff gets very messy.
Can you provide an example?
Almost anything where you want to partially borrow a struct member.
Is there any instance where you can create a
ref[...] ...
explicitly or where a = f()
with f -> ref[...] ...
does something else than a copy?It shouldn't try to copy until you pass a
ref
to something which needs owned
.
Try making a non-copyable, non-movable type, then putting it in a struct (foo), then doing var bazz = foo.bar
.
gives you the error
Same error with
Huh, I could have sworn that worked.