209 questions
7
votes
1
answer
142
views
Trait object taking ownership self
I want to build an application that interfaces with various cameras. Which specific camera is determined at runtime based on which is available. However, all cameras send frames one by one. Thus, to ...
14
votes
1
answer
484
views
Can a Box<dyn Any> have a lifetime less than 'static?
In Rust, the object Box<dyn Any> has a default life time of 'static. The compiler seems to accept using a different lifetime, for example Box<dyn Any + 'short>. However, this causes a ...
5
votes
1
answer
126
views
How do I tell if two trait objects refer to the same object in Rust?
In Rust I have a trait Node. I would like to determine if two &dyn Node refer to the same object.
I understand that &dyn Node is implemented as a fat pointer, with a base address and a vtable ...
3
votes
1
answer
107
views
Why are these two trait implementations not conflicting?
I have a situation in my codebase where i have one function which has a boxed trait object calling a function which expects an implementor of that trait, and i got the error message shown below. For ...
5
votes
1
answer
113
views
`T: Trait`/`impl Trait` doesn't satisfy `dyn Trait`, except when it does
I've encountered a strange variance behavior that I'm sure is a hole in my understanding of the type system, but feels like a compiler bug.
trait Trait: 'static {}
impl<T> Trait for T where T: '...
3
votes
1
answer
78
views
Generic Trait Parameters in Rust
I have a custom smart pointer which I'm trying to extend to trait objects. Essentially what I'm trying to make is the following:
use std::ptr::NonNull;
struct Ptr<T: ?Sized> {
data: NonNull&...
3
votes
1
answer
98
views
How can I create a Trait to represent all the type of data, except std::Any
What do I want
A Trait to represent all the type of data, like String,Vec<String>,i32, etc
Including some other complex data types, like Box<Arc<String>> and some of my customized ...
1
vote
1
answer
141
views
How to handle BufReader<File> and BufReader<Stdin> without dynamic dispatch?
I'm trying to create an object that can contain BufReader<File> and BufReader<Stdin> simultaneously. I'd like to avoid the more commonly used "trait object" (i.e. Box<dyn ...
2
votes
1
answer
488
views
Is there any way to use Associated Function of a trait in Rust?
I was experimenting with associated functions inside a trait's implementation, in order to use the trait's original implementation of the function. But I can't find a way to do that. My ...
1
vote
1
answer
293
views
Why are trait objects usually used via references (&dyn Trait) or smart Pointers (like Box<dyn Trait>)?
In Rust, why are trait objects usually used via references (&dyn Trait) or smart Pointers (like Box<dyn Trait>)? Does it have to be? Or is it better to use it this way?
4
votes
1
answer
2k
views
Understanding `impl dyn Trait`
I can't wrap my head around the second impl block. In my understanding, impl is typically used to implement a trait/methods on a concrete type like a struct. However, what does it mean to implement ...
0
votes
1
answer
622
views
What does Rust error "you could box the found value and coerce it to the trait object" mean?
What does this error mean?
Reproduction
error[E0308]: mismatched types
--> src/main.rs:50:35
|
50 | PaymentType::InvoiceIn => InvoiceIn {
| ___________________________________^...
0
votes
1
answer
183
views
Why can't trait methods have a default implementation returning self as a trait object
I am new to rust and trying to wrap my head around this error. If i use write this code
pub struct A {}
pub trait Trait {
fn stuff(self: Box<Self>) -> Box<dyn Trait>;
}
impl Trait ...
0
votes
0
answers
63
views
Conditionally enable Rust API only for `T = dyn Trait` type arguments
I have the following struct:
struct Struct<T: ?Sized = DefaultType> {
_phantom: PhantomData<T>,
}
impl<T> Struct<T>
where
T: ?Sized + MaybeAnotherBound,
{
fn ...
0
votes
0
answers
76
views
Size of types implementing a trait
I want to define a slice of MaybeUninit of trait objects, something like [MaybeUnint<dyn MyTrait>;2]. Of course, this doesn't work because Rust doesn't know the size of a dyn MyTrait at compile ...
0
votes
0
answers
138
views
How to implement a trait method that returns a trait object (of a different trait)
I'm studying Rust, and I'm struggling to replicate some OOP pattern using Rust's traits.
Briefly, I'd like to know what is Rust's way to solve this kind of problem. I have an interface whose methods ...
1
vote
1
answer
491
views
how to store multiple instances of dyn Trait, where Trait has associated types?
I'm learning rust, and a project idea I had was to write a command line parsing framework, that enables the use of commands and options. I have previously done this same project in other languages.
I ...
3
votes
1
answer
1k
views
Lifetime mismatch between function in async trait and implementations
Background
I'm trying to create a trait object with a single associated function, but that function needs to be async. So, I've been trying to use the async_trait crate to enable just that.
Problem ...
0
votes
0
answers
49
views
Attempt to create generic queries with Diesel - "first" method with incomplete trait bounds [duplicate]
I am trying to create a simple Rust CRUD app, using Diesel and a repository pattern.
My goal is to make the read/write methods generic, even if I know it might impact the code readability.
Here is my ...
5
votes
2
answers
716
views
What are the rules for coercing values to trait objects?
Consider the following Rust code:
#[derive(Debug, Clone, Copy)]
struct Struct;
trait Trait {}
impl Trait for Struct {}
fn f() {
// Why does this coerce to the target type (Result<Box<dyn ...
4
votes
0
answers
2k
views
Is static dispatch "almost always" faster than boxed dyn trait dispatch?
The pros/cons of using static vs dynamic dispatch have been addressed in a few related questions, e.g. 1, 2, 3.
From a performance perspective, it is intuitive to assume that dynamic dispatch (via ...
3
votes
3
answers
2k
views
Why doesn't Rust support trait objects with associated constants?
I know it's because of object safety:
Object safe traits can be the base trait of a trait object. A trait is object safe if it has the following qualities (defined in RFC 255):
...
It must not have ...
3
votes
1
answer
159
views
Rust trait object with generic type parameter
I have a trait Transformable which looks something like this:
pub trait Transformable {
fn position(&self) -> Vec2f;
fn set_position<V>(&mut self, position: V) where V: Into&...
4
votes
2
answers
380
views
How do you select a struct based on a string in Rust?
Problem Statement
I have a set of structs, A, B, C, and D, which all implement a trait
Runnable.
trait Runnable {
fn run(&mut self);
}
impl Runnable for A {...}
impl Runnable for B {...}
impl ...
2
votes
2
answers
398
views
Why does a method returning &Self makes a trait object-unsafe?
So I have been exploring/trying to understand static/dynamic dispatch, as well as trait objects in Rust. I think I get the gist of it. But there is still one thing that I cannot figure out: why does a ...
0
votes
0
answers
64
views
Implementing traits on boxed Fn trait generics leads to lifetime issues
Something of a beginner at Rust here. I'm trying to implement a trait, Ring, for functions that map data types that map types implementingRings to themselves. Ring looks like this:
trait Ring {
fn ...
1
vote
2
answers
203
views
Understanding Rust's Trait Objects and Lifetime Annotations in Different Function Signatures
I am studying the Traits and the Trait Object in Rust. In the Trait chapter, I solved the 6th exercise differently than the compiler suggestion. The following code defines two structs (Sheep and Cow) ...
2
votes
1
answer
163
views
How to add lifetime Parameter to Box<> with dyn type alias
I have an type alias for a Fn trait like type SomeSub = dyn for<'a> Fn(&'a str) -> &'a str; which I would like to use with a Box with an explicit lifetime like Box<SomeSub + 'b>....
1
vote
2
answers
82
views
impl trait with move method for trait object of same trait
I am trying to implement a trait on a boxed trait object of the same trait. I've done this before for trait whose methods take &self which works fine, but not self.
// The purpose of this trait is ...
2
votes
1
answer
824
views
How to unit test two implementations of a trait?
I have two structs implementing the same trait using a different algorithm.
I want to write the unit tests once and run them against both structs.
What is the best way to do this?
My concern is to ...
0
votes
1
answer
74
views
Problem with returning generic type from function
I have a function that searches through a list of trait objects and attempts to find one whose implementor is of a specific type, however the compiler doesent accept the return type.
pub struct ...
13
votes
1
answer
8k
views
How do I fix "cannot be sent between threads safely" when using tokio::spawn and Box<dyn Error>?
This simple program yields a compiler error:
#[tokio::main]
async fn main() {
tokio::spawn(async {
foo().await;
});
}
async fn foo() {
let f1 = bar();
let f2 = bar();
...
1
vote
1
answer
86
views
Store function returning impl Trait as trait object
As per the below example, I am trying to store functions as trait objects. I have worked out how to do this for functions which return a concrete type, by using as to cast from a function item to a ...
0
votes
1
answer
82
views
Blanket `impl Trait1` for all types which `impl Trait2` and functions which return `impl Trait2`
I want to implement HasChildren for all types which implement Element and for all functions which return impl Element.
My case use is that I have a Vec<Box<dyn HasChildren>> in which I ...
0
votes
2
answers
157
views
Rust impl multiple times both for struct and traits
Think below code, impl multiple times both for struct and traits:
mod m {
pub trait Foo {
fn xyzzy(&self) { println!("foo!"); }
}
pub trait Bar {
fn ...
2
votes
1
answer
238
views
The lifetime of trait object pointer
I encountered a compile error related to lifetime in my Rust code. Here is the code causing the error:
fn to_pointer_vec(ptrs: &[*const dyn ToString]) -> Vec<*const dyn ToString> {
...
0
votes
1
answer
110
views
Is there a way to implement trait objects with generic functions?
Basically I am trying to implement visitors-coding paradigm, where Expr trait needs to be implemented by Binary struct. I want to use Expr as a trait object. Any entity wanting to interact with Expr ...
2
votes
2
answers
646
views
How to cast Vec<Box<dyn SomeTrait + Send + Sync>> to Vec<Box<dyn SomeTrait + Sync>> in rust?
I'm failing to cast dyn SomeTrait + Send + Sync to dyn SomeTrait + Sync.
More specifically, I am trying to cast &Vec<Box<dyn SomeTrait + Send + Sync>> to &Vec<Box<dyn ...
0
votes
1
answer
108
views
Storing an iterator over borrowed refs inside a Struct
I'm new to Rust and like many finding lifetimes quite hard to get the hang of. I get the basics, but I can't quite fathom how to make this work.
I'm trying to implement an abstract data structure that ...
1
vote
1
answer
236
views
Why can't I clone a `Vec` of cloneable constructors?
I have a structure wrapping a Vec of Box<dyn Any> constructors which I've asserted to be clone.
I have a trait Ctor which takes the clone logic and produces another Box<dyn Ctor>. It ...
0
votes
1
answer
191
views
What happens when I pass a concrete struct reference to a function that takes trait objects?
In the following code I have a simple trait, A, and a struct Foo that implements A...
Next, I define a function that takes a reference to a trait object. From main() I pass in a reference to a ...
0
votes
1
answer
183
views
How can I avoid allocation when filtering on a set of items with a higher order function?
Trying to filter a set of items, based on a predicate that is generic, because computed at run-time:
fn main () {
let el = vec![
vec![10, 20, 30],
vec![40, 50, 60]
];
...
0
votes
1
answer
196
views
Trait objects force higher-ranked trait bounds, which break nested closures
I am in a situation where Rust makes me add a HRTB for a generic type that is used as argument in a trait object. But this HRTB makes nested closures not work.
Here's the trait I'm going to use to ...
0
votes
2
answers
192
views
Trait object as associated type of a trait object
I wrote two structs that implement a common trait Solve. Solve has an associated type Answer with trait bound Display. I want the function create_solver to return a trait object of Solve.
I need help ...
2
votes
0
answers
92
views
Rust trait objects: specific use case of variance and/or coercion
Consider the following (playground)
trait Module {}
struct Foo {
module_box: Box<dyn Module + 'static>,
module_rc: Rc<dyn Module + 'static>,
}
impl Foo {
fn mut_box<'s>(...
0
votes
2
answers
84
views
Clone custom structs of concrete type as trait objects [duplicate]
Using Rc, I can cast an Rc of a concrete type to a trait object:
use std::rc::Rc;
trait Foo {}
impl Foo for usize {}
fn main() {
let x: Rc<usize> = Rc::new(1);
let y: Rc<dyn Foo>...
2
votes
1
answer
121
views
Error E0277 following book example dyn Trait, how to push a dyn trait in vector?
My real case is similar to the Rust doc about dyn trait with Screen and Draw trait.
So I built an example totally similar to the book. But instead of initializing the vector in place, I need to have a ...
0
votes
1
answer
829
views
How can I create a variable to a trait with an associated type in Rust?
I want to create a variable that holds a trait. The trait implementation is unknown during compile time. Hence, I need a trait object. This works with "normal" traits but not when the trait ...
0
votes
2
answers
110
views
Cannot relax lifetime of Trait Object
I have the following code:
use tokio; // 1.7.1
use futures::future::Future;
use std::pin::Pin;
use futures::FutureExt;
use std::marker::PhantomData;
use std::marker::Send;
use std::sync::Arc;
use ...
3
votes
2
answers
2k
views
Rust serde deserialize dynamic trait
I have a recursive data structure in my pet-project:
(this is a simplified example)
pub trait Condition {
fn validate(&self, s: &str) -> bool;
}
pub struct Equal {
ref_val: ...