Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Pointers are used reference things allocated from the heap, and never anything else, unless you're insane.

People routinely use pointers to things on the stack in several languages. Rust even makes it safe to do that, using lifetimes - a pointer to something on the stack can't outlive the stack frame it points into.

> I don't see why anyone wouldn't copy values by default...

Because not everything is safe to copy. In particular, Rust has a few kinds of pointers which come with special rules.

Firstly, it has boxes, which always point to something on the heap, and have a rule that that when the pointer dies, the thing it points to gets freed. If you copied a box, then when one of the copies died, the thing would be freed, and then the other copy would have a pointer to invalid memory, which would be bad.

Secondly, it has mutable references, which come with a guarantee that a mutable reference is the only pointer to a given thing. If you copied a mutable reference, you would break that guarantee.

Thirdly, it has reference-counting pointers (these are in the standard library, not the language). You can make duplicates of those, but they have to increment their reference count when you do so. Copying is always just a bitwise copy, so there is no chance to increment the reference count. Instead, duplication is an explicit operation.

There are a few other things it doesn't make sense to copy. Like, what would it mean to copy a mutex?

So, in Rust, you can't copy by default. However, it is really easy to mark a type as being copyable (the compiler will check that it really is, ie doesn't contain any non-copyable things), and then you can copy it.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: