This assumes that every value in Rust implements either the Clone
or the Copy
trait. Is this assumption true?
No.
is it possible to define a trait Duplicate
Yes, but it doesn't seem to serve any value beyond what the existing Clone
trait does.
You may wish to learn more about ownership, as you can make your code compile without doing any cloning at all:
fn duplicate<T>(x: T) -> T { x } // sic
fn main() {
let a = 7;
let b = duplicate(a);
let a = String::from("example");
let b = duplicate(a);
}
If you actually want to duplicate, just use Clone
, as anything that implements Copy
must implement Clone
:
pub trait Copy: Clone { }
You will usually see it as the method syntax:
fn main() {
let a = 7;
let b: i32 = a.clone();
let a = String::from("example");
let b: String = a.clone();
}
If you want a function, use the fully-qualified syntax:
fn main() {
let a = 7;
let b: i32 = Clone::clone(&a);
let a = String::from("example");
let b: String = Clone::clone(&a);
}
Or
fn main() {
let a = 7;
let b: i32 = i32::clone(&a);
let a = String::from("example");
let b: String = String::clone(&a);
}
All the explicit types (: foo
) are redundant here, just for demonstration purposes.