I have an autogenerated struct named Address by protobuf in Rust. It has a predefined Debug trait like this:
impl ::std::fmt::Debug for Address {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
But I want to customize how it's printed when {:#?} is used. So I decided to implement Debug trait for it like this in my project:
impl fmt::Debug for EvmProto::Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
....
}
}
But it complains that conflicting implementations of trait `std::fmt::Debug` for type `protos::Evm::Address
UPDATE: while the answer can still be useful in some similar cases, in this case it seems incorrect. See the comments for details.
You can't implement an external trait on an external type.
I'm citing The Rust Book
we can’t implement external traits on external types. For example, we can’t implement the Display trait on Vec<T> within our aggregator crate, because Display and Vec<T> are both defined in the standard library and aren’t local to our aggregator crate. This restriction is part of a property called coherence, and more specifically the orphan rule, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn’t know which implementation to use.
Related
I came across some code I don't fully understand where the trait being impl is the same as the where clause. For example the futures::future::Map struct includes the debug implementation
impl<Fut, F> Debug for Map<Fut, F>
where
Map<Fut, F>: Debug,
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>
This seems to me to indicate that Debug should be implemented for Map struct when debug is already implemented. This is confusing as it seems as if this implementation would never be called yet it obviously works correctly. Apologies for the beginner question but I haven't been able to find anything in the book and I don't really know what to google here. Am I missing a key something about how trait implementations and bounds work?
After reading the source code (which is not made is since all these implementations are macro-generated), it seems to me that the second Map corresponds to an internal type, namely map::Map. It's a bit unfortunate how the doc is rendered.
This question already has an answer here:
Can I get a trait object of a multi-trait instance without using a generic type?
(1 answer)
Closed 10 months ago.
In rust I would like to have a vec containing items which implement 2 traits. However when I try to implement it like so, I get the error only auto traits can be used as additional traits in a trait object:
let mut v : Vec<Box<dyn MyTrait + std::fmt::Display>> = Vec::new();
FairPlay, I read the error message in full and defined a Trait which combines the two:
pub trait FormattableDoer: std::fmt::Display + MyTrait{}
The have a Vec of Boxes to that:
let mut v: Vec<Box<dyn FormattableDoer>> = Vec::new();
However the compiler can't seem to detect that my struct has implemented those things separately and I get the error the trait bound MyStruct: FormattableDoer is not satisfied.
I read about using a trait alias, but that's not in stable so I'd rather not use it.
Is this possible in rust? It seems like a common thing to want to do and I'm surprised that the answer isn't simple (or maybe it is and I have missed it!). I'm also thinking that maybe I have approached the problem all wrong and I'm attempting to do something in an 'non rusty' way. If that's the case, what is the preferred way of having a vector of things which are displayable and have some other trait?
Playground with a MWE and a use case.
You're almost there. You need a marker trait that implements both parents, as you've already done
pub trait FormattableDoer: std::fmt::Display + MyTrait {}
Then you need a blanket implementation which takes those two traits to your new trait.
impl<T: std::fmt::Display + MyTrait> FormattableDoer for T {}
Now everything that implements std::fmt::Display and MyTrait will implement FormattableDoer automatically, and since FormattableDoer is a single trait, it can be used as a trait object.
Then just use Box<dyn FormattableDoer> like you've already tried.
You still need to implement FormattableDoer for your struct. In the playground you posted, you're not doing that. Simply add
impl FormattableDoer for MyStruct {}
and you should be all done.
No user-defined traits are auto-implemented, even if they contain no methods or associated types.
On the documentation it is stated that
impl<T> Borrow<T> for T where
T: ?Sized,
I would read this:
This Trait is implemented for every Type, even unsized ones.
Is this correct?
I got the error message:
the trait std::borrow::Borrow<T> is not implemented for &num_complex::Complex<f64>
which I can't make sense of.
(I do not want to post the whole code, I just want some clarification about which types implement std::borror::Borrow)
The important thing to recognize is that in the blanket impl there is only one T and it has to represent the same type in both places:
impl<T> Borrow<T> for T
where T: ?Sized
implements for each type T, only the specific trait Borrow<T>. i64 implements Borrow<i64>, String implements Borrow<String>, etc. When we instantiate this with T = &num_complex::Complex<f64>, what trait is implemented?
impl Borrow<&num_complex::Complex<f64>> for &num_complex::Complex<f64> // (not compilable code, just illustrative)
In words, you can borrow a &Complex<f64> as a &Complex<f64>, but you can't borrow it as any arbitrary T (which wouldn't make much sense, anyway).
You're using this in some generic code where T can be anything, so the blanket impl of Borrow<T> for T doesn't apply. You can probably fix this by adding a trait bound:
where num_complex::Complex<f64>: Borrow<T>
which means that Complex<f64> itself implements Borrow<T>, or
where for<'a> &'a num_complex::Complex<f64>: Borrow<T>
which means that any reference to Complex<f64> implements Borrow<T>. Depending on your actual code either or both of these may work due to autoref/autoderef.
Why does FlatBufferBuilder from the Rust flatbuffer library have a lifetime associated with it?
The lifetime makes it difficult to use in structs, as I then need to add a lifetime to them. I see that the lifetime is used for a few methods, but it seems like those could use the lifetime of self instead.
New to Rust myself so was trying & struggling to deal with this too.
From looking at flatbuffers's builder.rs code, seems to be due to the fact that methods like below return references to data inside the builder, which needs to know the builder's lifetime to be valid.
pub fn create_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str>
Using 'static like Matthieu mentioned above appears to enable me to not add more explicit lifetimes to structs that have a member FlatBufferBuilder. But still struggling to understand why putting 'static on a struct that isn't static is working ...
I'm trying to extend the Grid struct from the piston-2dgraphics library. There's no method for getting the location on the window of a particular cell, so I implemented a trait to calculate that for me. Then, I wanted a method to calculate the neighbours of a particular cell on the grid, so I implemented another trait.
Something about this is ugly and feels unnecessary seeing as how I'll likely never use these traits for anything other than this specific grid structure. Is there another way in Rust to extend a type without having to implement traits each time?
As of Rust 1.67, no, there is no other way. It's not possible to define inherent methods on a type defined in another crate.
You can define your own trait with the methods you need, then implement that trait for an external type. This pattern is known as extension traits. The name of extension traits, by convention, ends with Ext, to indicate that this trait is not meant to be used as a generic bound or as a trait object. There are a few examples in the standard library.
trait DoubleExt {
fn double(&self) -> Self;
}
impl DoubleExt for i32 {
fn double(&self) -> Self {
*self * 2
}
}
fn main() {
let a = 42;
println!("{}", 42.double());
}
Other libraries can also export extension traits (example: byteorder). However, as for any other trait, you need to bring the trait's methods in scope with use SomethingExt;.
No. Currently, the only way to write new methods for a type that has been defined in another crate is through traits. However, this seems too cumbersome as you have to write both the trait definition and the implementation.
In my opinion, the way to go is to use free functions instead of methods. This would at least avoid the duplication caused by traits.