4 ms·
"I don't understand why b=a; c=a; <-- doesn't work because a is "used up"???" Had the same issue a few months ago. The pointer can only be referenced by one v
by k__ 6y ago
"I don't understand why b=a; c=a; <-- doesn't work because a is "used up"???"
Had the same issue a few months ago.
The pointer can only be referenced by one variable at a time.
If you "move" the pointer from a to b then a is figuratively "used up" because a is now blocked from doing anything with the pointer anymore.
I guess, for Rust itself the pointer is still referenced by a, Rust just blocks you from using it. But thinking you moved it to another variable helped me a bit.
- mikewarot 6y agoif I say a = 2; b = a; c = a; There's no pointer in there, just 2.
- rcxdude 6y agoThat will work fine, because 2 is 'Copy', so it can be copied trivially (as are structs consisting only of Copy members which are marked as Copy). Roughly speaking anything with a pointer in it isn't Copy, though many objects will implement Clone, which basically just means you need to explicitly call .clone() to make a copy instead of it happening implicitly.
- mikewarot 6y ago2 is Copy? It's an integer, could be 2.0 if you wanted to make it a float. Someone needs to explicitly nail down the mission statement of Rust... because to me it seems to be "Rust will introduce pointers where they don't need to be, and then try to protect you from the results with obsessive rules"
- fasterthanlime 6y agoI wrote a piece that tries to explain Rust's memory management strategy, compared to C: https://fasterthanli.me/articles/declarative-memory-management https://fasterthanli.me/articles/declarative-memory-manageme... Hope it helps!
- AsyncAwait 6y agoYou need to seriously read more on Rust before making judgments. You're clearly confused. What '2 is Copy' means precisely that Rust WILL NOT 'introduce pointers where they don't need to be' - 2 is fine to 'alias' because it's a primitive type and so a copy is made when you do that, (i.e. the type implements the 'Copy' trait). However when you do that with complex types that do not implement Copy, you're moving ownership to the new variable so cannot use the old one any more.
- zRedShift 6y agoYes, primitive types all implement Copy. Maybe playing around with the code would help you better, because that last line doesn't make any sense: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4a552d32870679667470f2acc9940a74 https://play.rust-lang.org/?version=stable&mode=debug&editio...