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 ...
Related
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.
In the book Rust for Rustaceans, the author writes:
Broadly speaking, though, you’ll want to use static dispatch in your libraries and dynamic dispatch in your binaries. In a library, you want to allow your users to decide what kind of dispatch is best for them, since you don’t know what their needs are.
I guess that, in the binary case, he refers to this:
fn flexible_dispatch_method(_: &dyn MyTrait) {}
// static dispatch
//
let obj = MyType {};
flexible_dispatch_method(&obj);
// dynamic dispatch
//
let trait_obj: &dyn MyTrait = &MyType {};
flexible_dispatch_method(trait_obj);
Given the above, what's the advantage of using boxed objects instead of trait objects? Is it because of the need to use lifetimes:
fn return_new_trait_object<'a>() -> &'a dyn MyTrait {
&MyType {}
}
or there is something else? Based on my understanding, in the dynamic dispatch case, the object needs to be allocated in the heap, anyway, so I presume there isn't much difference with a boxed object.
I think you might be misunderstanding a couple things here.
(Generally) static dispatch occurs whenever you call a method on a concrete type that's not dyn Trait. It's when the compiler decides which function to call at compile-time.
A trait object is anything that's some pointer to a dyn Trait, including Box<dyn Trait>, &dyn Trait, Arc<dyn Trait>, etc. When you call a function through a dyn Trait, the compiler inserts code to lookup the function to call at runtime, allowing for polymorphism and greater flexibility.
In your code, flexible_dispatch_method(_: &dyn MyTrait) always uses dynamic dispatch, as signaled by the fact that its argument has the type &dyn MyTrait. An example of static dispatch would be the following:
fn flexible_dispatch_method<T: MyTrait + ?Sized>(_: &T) {}
With this declaration your first usage would use static dispatch and the second would use dynamic dispatch.
Dynamic dispatch is a little more flexible since it avoids having generics all over the place. This can be useful for writing large applications where you might want to have polymorphism and easily add new implementations. However, dynamic dispatch has a performance cost, so that's why libraries should leave the dispatch choice up to the caller as much as possible.
As per when to use &dyn Trait vs Box<dyn Trait>: it's all based on ownership. If you want an owned trait object use Box<dyn Trait>, and if you want a borrowed trait object use &dyn Trait.
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.
Edit: Question as the title modified by Shepmaster. Added more details to the situation.
I'm wanting to have access to an object following a trait in different threads, stored overall in a struct. As I'm porting my code from another language to try to learn rust, I'm still a bit of a newbie to the language.
Originally I thought to have a struct similar to the following, which compiled fine:
struct MyStruct<T : MyTrait> {
my_object : Arc<Mutex<T>>
}
However, ultimately I need to store a reference to to it as it will be stored in multiple threads. I understand I need to use lifetimes as well to get this to work, so I ended up with the following:
struct MyStruct<'a, T : MyTrait> {
my_object : &' Arc<Mutex<T>>
}
The error I get is:
error[E0309]: the parameter type T may not live long enough
-- help: consider adding an explicit lifetime bound T: 'a...
...so that the reference type &'a std::sync::Arc<std::sync::Mutex<T>> does not outlive the data it points at
my_object : &' Arc< Mutex < T > >
The error implies that I have to specify the lifetime to my generic, however, I already have a trait for my type. So Ultimately, how can I specify that a generic type both follow a trait and have a lifetime?
Ultimately, how can I specify that a generic type both follow a trait and have a lifetime?
The same way you'd specify multiple traits: add them with +. I.e. T : MyTrait + 'a