Reputation: 8096
Somewhat new to Trait implementation/usage:
If I declare a trait thus:
pub trait A: Debug + Clone {
fn as_base58_string(&self) -> String;
fn as_bytes(&self) -> [u8; 32];
}
With a concrete implementation:
impl A for P {
fn as_base58_string(&self) -> String {
self.to_base58_string()
}
fn as_bytes(&self) -> [u8; 32] {
self.to_bytes()
}
}
And have a function like:
pub fn print_akey(akey: &dyn A) {
println!("A{:?}", akey);
}
I am getting this error
the trait `A` cannot be made into an object`A` cannot be made into an object
Even though the concrete type P
is cloneable?
If I remove Clone
from the trait declaration the warning goes away/
Upvotes: 0
Views: 318
Reputation: 71605
Clone
is not object safe. That means you cannot create a dyn Clone
, and thus you cannot create dyn Trait
for any Trait
that has Clone
as a supertrait.
The reason for that is that Clone::clone()
returns Self
, and one of the rules for object safe traits is that they must never mention the Self
type (outside of &self
or &mut self
).
If you want to clone a trait object (dyn Trait
), see How to clone a struct storing a boxed trait object?.
Upvotes: 2