简体   繁体   中英

How to create a trait that specifies the associated type of a supertrait?

I want to create an abstract trait that specifies an indexing type and a value type where any struct that implements the trait has to implement Index<IndexType> and IndexMut<IndexType> and defines the Output type which stays the same in every struct that implements the trait.

I tried creating a trait, but it seems I can't specify the output type:

use std::ops::{Index, IndexMut};

struct Coord;
struct LightValue;

trait LightMap: Index<Coord> + IndexMut<Coord> {}

impl LightMap {
    type Output = LightValue;
}
warning: trait objects without an explicit `dyn` are deprecated
 --> src/lib.rs:8:6
  |
8 | impl LightMap {
  |      ^^^^^^^^ help: use `dyn`: `dyn LightMap`
  |
  = note: `#[warn(bare_trait_objects)]` on by default

error[E0191]: the value of the associated type `Output` (from the trait `std::ops::Index`) must be specified
 --> src/lib.rs:8:6
  |
8 | impl LightMap {
  |      ^^^^^^^^ associated type `Output` must be specified

error[E0202]: associated types are not yet supported in inherent impls (see #8995)
 --> src/lib.rs:9:5
  |
9 |     type Output = LightValue;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^

If I don't specify the output type then associated type Output must be specified happens wherever I try to use the trait.

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