New Rust user here, so forgive me if this is a trivial question.
I noticed that the clone
function of the Clone
trait returns something of type Self
. Trying to change that to Option<Self>
, for instance, will fail, with the compiler saying that it's not the type it's expecting.
Having a clone function that can fail seems perfectly natural, though. For instance right now I'm wrapping a C library in Rust, and the C library has a function to duplicate an object. This duplicate function can fail, returning a negative value if it does. If I were to just implement the Clone
trait for the corresponding Rust type, the only way I can handle the error is to panic if the return value is not 0.
Alternatively, I could implement a clone
function that returns an Error<Self, ...>
without implementing the Clone
trait. Or I could call this function duplicate
to make it clear that it it's not the clone
function from the Clone
trait...
What is the idiomatic way in Rust to return an error from a clone operation that can fail?
More generally I can see other traits with functions that don't let me return an error. I could want to implement the ToString
trait but to_string
function returns a String
, while internally the C function that will provide me with that string can fail.