Here's the scenario: I have a structure and trait pair as follows:
trait Operation {
fn operation(self) -> u32
}
struct Container<T: Sized + Operation> {
x:T
}
impl <T: Sized + Operation> for Container<T> {
fn do_thing(&self) -> u32 {
// Do something with the field x.
}
}
The operation requires a pass-by-value call whenever used, and the issue comes with anything similar to "do_thing." I would prefer to not have to enforce copy semantics for the type T
and would like a workaround for this. Essentially I would like to know the following:
struct Container<T: Sized + Operation> where &T: Operation { ... }
. I've tried mucking with the syntax a bit, and I've not had any success.Middle: Operation
, where Middle
can require that any implementers of Middle
, T
, to also be required to implement Operation
for &T
.Some Notes:
Operation
trait, it's given and it's what I'm to work with.Yes, you can restrict &T
to be Sized + Operation
. You need to use Higher-Rank Trait Bounds and where
.
trait Operation {
fn operation(self) -> u32;
}
struct Container<T>
where for<'a> &'a T: Sized + Operation
{
x: T,
}
impl<T> Container<T>
where for<'a> &'a T: Sized + Operation
{
fn do_thing(&self) -> u32 {
self.x.operation()
}
}
impl<'a> Operation for &'a u32 {
fn operation(self) -> u32 {
*self
}
}
fn main() {
let container = Container { x: 1 };
println!("{}", container.do_thing());
}
prints
1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With