Rust restrictions to describe the general type

Here's the scenario: I have a structure and a couple of signs 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 parcel call whenever it is used, and a problem occurs with something similar to "do_thing". I would prefer not to use copy syntax for type T and would like a workaround for this. Essentially, I would like to know the following:

  • Is it possible to apply restrictions on binding to type parameter links? Something like: struct Container<T: Sized + Operation> where &T: Operation { ... } . I tried a little mess with the syntax, and I had no success.
  • If this is not possible at present, it is theoretically possible; that is, it does not violate any requirements of coherence or something in this direction?
  • Is it possible to create a second attribute, say Middle: Operation , where Middle can require that any executors of Middle , T also be required to implement Operation for &T
  • If none of the above is possible, is there some other workaround for this?

Some notes:

  • I do not have access to change the sign of Operation that he gave, and I have to work with this.
  • There is an old RFC that talks about some changes to where clauses, but I did not find anything related to reference restrictions.
  • compiler version: rustc 1.8.0 (db2939409 2016-04-11)
+6
source share
1 answer

Yes, you can limit &T Sized + Operation . You should use Higher Grades 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 
+9
source

All Articles