Hacker News new | ask | show | jobs
by umanwizard 2000 days ago
> Why not hide it a bit by letting the implicit copy to happen to simpler structures.

This is already the case. Built-in types that are simple enough to be copied implicitly already are (roughly: those which don't manage any memory or other resources), and you can enable this for your own types with `#[derive(Copy)]`, as long as they are composed only of implicitly copyable types.

    #[derive(Copy)]
    struct S {
        x: i32,
        y: usize,
        z: Option<Result<(), ()>>,
    }

    fn f(x: S) {
        // ...
    }

    fn main() {
        let s = S { x: 0, y: 0, z: Some(Ok(())) };
        f(s);
        f(s);
    }

Something like `String` isn't implicitly copyable in Rust, because it manages memory, and therefore copying it would require a heap allocation.

The Rust way of forcing non-trivial clones to be explicit is much better than C++ IMO, where someone forgetting a `&` or an `std::move` somewhere can cause an innocuous-looking function call to be arbitrarily slow.

In C# there are not implicit copies either (except of value types), because more complex types in C# are accessed via pointers to garbage-collected heap objects. Rust doesn't have a garbage collector, though.

1 comments

The misunderstanding may come down to the fact that strings are "primitives" in many languages - for usability reasons - despite carrying the memory/performance traits of a full, heap-allocated "object". If someone has never worked in a language where strings are not primitives, I can see how they might be irked/confused by suddenly having to deal with that.