简体   繁体   中英

rust: huge generic constructors, nested trait

In the effort to keep a library I have been working on fairly generic, I find my self writing this huge code to just construct a struct:

pub struct SampleRenderer<Camera_T, Sampler_T, SurfaceIntegrator_T, Filter, Sample_Iter> {
  camera : Camera_T,
  sampler : Sampler_T,
  surface_integrator : SurfaceIntegrator_T,
  film : Film<Filter>,
}

impl<Camera_T, Sampler_T, SurfaceIntegrator_T, Filter, Sample_Iter> SampleRenderer
    <Camera_T, Sampler_T, SurfaceIntegrator_T, Filter, Sample_Iter> {
  pub fn new<Camera_T : Camera, Sampler_T : Sampler<Sample_Iter>, SurfaceIntegrator_T : SurfaceIntegrator, Filter, Sample_Iter>
    (camera : Camera_T, sampler : Sampler_T, surface_integrator : SurfaceIntegrator_T, film : Film<Filter>)
    -> SampleRenderer<Camera_T, Sampler_T, SurfaceIntegrator_T, Filter, Sample_Iter> {
    SampleRenderer {
      camera : camera,
      sampler : sampler,
      surface_integrator : surface_integrator,
      film : film
    }
  }
}

While this works, it is a pain to work with and very repetitive. Each input has a trait associated with it, and some of these traits are templated as well (Sampler).

Does anybody have a cleaner way to express this? Am I looking at the problem all wrong?

Thanks!

You can simplify your code by omitting type parameters in new() definition, that is, you don't need to write new<Camera_T : Camera, Sampler_T : Sampler<Sample_Iter>, SurfaceIntegrator_T : SurfaceIntegrator, Filter, Sample_Iter>() , you can write just new() . Corresponding parameters will be taken from impl<...> clause.

Other that this, I think, you're out of luck. Type parameters syntax requires you to type all these names. In fact, you'll do the similar thing in other languages as well. You can try and use simpler, one-letter names for type parameters; given their number it can be less readable, but at least you can try it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM