|
|
|
|
|
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. |
|