Trait object with associated types in field - requires generic param?

I currently have:

trait ListModel {
    fn get_stuff(&self, row: i) -> Stuff;
    ...
}
struct List {
    model: Rc<dyn ListModel>,
    ...
}

I think I want to change my model to use row IDs instead of usize indices. If I do this:

trait ListModel {
    type Key: Eq + Hash + Clone;
    fn get_stuff(&self, row: Key) -> Stuff;
}

There is no way to keep List non-generic, correct? I need to have something like these? :

struct List<M: ListModel> { 
    model: Rc<M>,  
}
// or
struct List<K> { 
    model: Rc<dyn ListModel<Key = K>>,
    ...
}

You can define a second trait, blanket implemented for the first trait, that has no associated type, but in order for this to be useful for anything, that second trait would need to provide some way to work with the keys (e.g. maybe through an enum or dyn Any) or operations that don’t depend on the key type (e.g. listing all rows regardless of key).

it might be possible to erase the M: ListModel type in some cases, but it's not that straight forward, you need multiple levels of indirection.

the problem is, in order to erase M: ListModel, you must also erase the associated type <M as ListModel>::Key, but in your example, the none of the bounds on Key, Eq, Hash, Clone, is dyn compatible, so you need to find some trickery to erase them first.

the key idea is to design an erased type that can dynamically dispatch the required Key operations at runtime, which means, you need adapters for Eq, Hash, Clone. note, Clone is the most tricky one, since it has a method with Self as the return type, the other two are relatively easy. but you do need to check the type at runtime, e.g. with Any. e.g.something like this:

trait ErasedKey: Any {
	fn dyn_eq(&self, rhs: &(dyn ErasedKey + '_)) -> bool;
	fn dyn_hash(&self, hasher: &mut dyn std::hash::Hasher);
	fn dyn_clone(&self) -> Box<dyn ErasedKey + 'static>;
}

however, the real question is: what happens if the runtime type check failed?

the fact the Key type is an associated type means the type is chosen by the implementor of ListModel. but it is used as an argument of the method get_stuff(), so if you erase the type, the client code will not be able to call the method unless they know the real key type, otherwise you get a runtime type mismatch (e.g. a failed Box<dyn Any>::downcast())!

conclusion: it's pointless to erase the key type given the current ListModel design. you either keep the generic parameter on struct List<K>, or you redesign the ListModel trait to be dyn compatible (or at least meaningfully erasable).

Well, where are your keys coming from in the first place, like your usize keys? And what happens when the user passes in some nonsense usize values?

The dyn ErasedKey or enum KeyType approaches allow passing in things that are arguably even more nonsense, and the fully generic version in particular[1] introduces the risk of accidentally coercing e.g. &Box<KeyTy>[2] instead of &KeyTy.[3] Not to mention the costs of boxing and indirection. So there are new hazards.[4]

But if the "must coordinate keys back to the origin correctly" and "what to do with junk input" problems aren't entirely new, relative to the original trait.

Here's a sketch of the approaches (but I probably wouldn't use either without a solid reason to).


  1. as opposed to supplying a macro to implement the erased trait for specific types ↩︎

  2. func(&bx_of_key_ty) ↩︎

  3. func(&*bx_of_key_ty) ↩︎

  4. With either approach I'd keep the associated type version around so that the cleaner / more efficient API is still available. ↩︎

There possibly is an XY type solution for this too: for example if this is some kind of database type API, you could keep your keys serialized and do a simple byte array comparison, and only parse when needed.

This code comes from my UI library, where I have two UI widgets, List and Tree, that display a dynamic scrolling view of many children widgets. I used a pattern (rustified) that I've seen going way back, where a TreeModel or ListModel provides a view of the data as well as methods to provide widgets for each "row/node", like create_widget and bind_widget.

So about what you say above – the user of the ListModel trait is the List widget, and it gets IDs from it's model. They are not really used by the List other than to refer to rows/nodes with the model.

It's just that with some models it's convenient to have different types of IDs - strings, Uuids, maybe integers. Right now my code is actually not generic. Just to get things working I have:

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RowKey {
    Index(usize),
    Uuid(Uuid),
    Text(Arc<str>),
}

My response to @nerditation may have answered this. The keys come from the models (ListModel or TreeModel). Something like:

trait ListModel {
    fn first(&self) -> Option<Key>;
    fn next(&self, key: &Key) -> Option<Key>;
    fn prev(&self, key: &Key) -> Option<Key>;
    
    // and then...
    fn row_kind(&self, key: &Key) -> RowKind;
    // Not bound to data yet. Widgets can be re-used during scrolling. 
    fn create_widgets(&self, kind: RowKind) -> Widgets;
    // Sets the text, icons, etc, of the widgets, based on the data 
    // at `key` in the model.
    fn bind(&self, kind: RowKind, widgets: &mut Widgets, key: &Key);

does that mean the type of the key is opaque to the caller? if that's the case, than it can be an erased type chosed by the implementor.

however, you still need to query the key (let's call it the internal key) from the model in the first place, no? how do you do that? you must use some type (let's call it the external key type) that is known to the caller, like an integer index, right?

so if I understand this correctly, the opaque "key" type (the internal key) really is an implementation detail? then why expose it in the api? why not just use the external key directly?


my point is, an associated type is chosen by the implementor, not the caller. you can erase the type at compile time with some indirections, but you CANNOT eliminate the type check, it just moves to runtime.

in any case, I feel like this is probably an XY problem. whatever the referenced OOP pattern is, this is definitely not the best way to "rustify" it.

in traditional GUI framework, the interface between a widget and its data model is defined by the widget, not by the data. it's the implementor's job to create an adapter when the data shape does not fit the model api.

in the linked java doc, the tree traversal api of the TreeModel interface looks like this:

Object getChild(Object parent, int index) Returns the child of parent at index index in the parent's child array.
int getChildCount(Object parent) Returns the number of children of parent.
int getIndexOfChild(Objectparent,Object child) Returns the index of child in parent.
Object getRoot() Returns the root of the tree.
boolean isLeaf(Object node) Returns true if node is a leaf.

as you can see, it uses integer indices to locate a node, the implementor cannot choose a different key type.

I didn't find a link to a TreeModel from the java docs, but I imagine a trait that is most faithful to the java design might look like this:

// emulate the java `Object` class, to represent a fully erased Node
// use `Any` as super trait to support downcasting
trait Object: Any {
    /// for display purpose, mirror of `ToString::to_string()`
    /// alternatively, can also mirror `Display::fmt()`
    fn to_string(&self) -> String;
    fn eq(&self, other: &dyn Object) -> bool;
    fn hash(&self, hasher: &mut dyn Hahser);
    fn clone(&self) -> Box<dyn Object>;
}

trait ListModel {
    fn stuff_count(&self) -> usize;
    /// depending on the design, alternatives may return different type than Box
    ///  for example, `&'_ dyn Object`, `Arc<dyn Object>`, etc
    fn get_stuff(&self, i: usize) -> Box<dyn Object>;
}

even if you were to mimic the java api, add an associated Key type (and then just to erase it when stored???) definitely makes little sense. but again, the java api isn't the most idomatic way to design a rust gui library anyway.

what's the best solution? well, it's hard to give one single best, or a better answer, without the full context of your use case. but many rust gui libraries either use some functional style api or immediate mode api, generally they don't use OOP style "abstract" interface to represent data models. you usually just use simple data structure of value types (e.g. &str) instead of some opaque "objects". to render arbitrary data structure, just convert them to strings.

for example, in iced, to display a list of items, you just use an array/slice of any type that implements Display:

let options = ["item 1", "item 2", "item 3"];
let selected = Some("item 2");
pick_list(&options, selected, on_selection_change).into()

They use an integer to get a child of a given node, but the Object is identifying that node, in the way I'm using my row keys/ids. So in sense the Java API is using type erased keys. Object ≈ Any. Because they use Object, their "key" could also be the data, as opposed to a key to get the data. But that gets uglier in Rust because you need to use Rc or Arc so I prefer IDs/keys.

I'm not sure what you mean here. If you mean how does List or Tree (the UI widgets), first get a key from ListModel or TreeModel, the answer is a method on the model like root() or as I showed for ListModel, first() which returns a key, assuming the list isn't empty. Then from there are iterator-style methods like next/prev/first_child to lazily expose more of the data.

List/Tree are in the UI library, while the model traits are implemented by the app-specific code. For example, I have a Tree that browses a folder/document structure defined in a SQLite database. So the model in that case was using Uuid to identify the database records of the file or directory tree "nodes".

That example works for a 5-item list, but part of why my model traits are more complex is that these widgets are lazy - they can scroll and lazy-load a tree or list with 1000's of items (or even infinite amounts of data).

You might be interested in the egui virtual list support, which gets away with a very simple implementation completely based on the item index: ScrollArea in egui::containers::scroll_area - Rust

I suspect you could get away with just that, given the lack of a GC to make widget re-use especially attractive - I've used that for ~10k lists easily, and it should work fine for millions (really, even naive Rust UI implementations tend to be pretty hilarousally efficient to what you might be used to elsewhere)

But I think your desired model should work fine, if you just pick the right layer to erase. Something like this?

trait ListModel {
  type Key: Eq + Hash + Clone;
  type Item: Widget;

  fn create_widget(&self) -> Self::Widget;
  fn bind_widget(&self, key: &Self::Key, widget: &mut Self::Widget);
}

impl ListModel for Vec<String> {
  type Key = usize;
  type Item = Label;

  fn create_widget(&self) -> Label {
    Label::new()
  }

  fn bind_widget(&self, key: &usize, widget: &mut Label) {
    widget.text.clone_from(self[*key]);
  }
}

struct List<Model: ListModel> {
  model: Model,
  // IndexMap preserves order but also allows lookup by key
  items: indexmap::IndexMap<Model::Key, Model::Widget>,
  // other stuff, e.g.
  selection: Option<Model::Key>,
}

impl<Model> Widget for List<Model> where Model: ListModel {
  // ...
}

That is, the Widget trait is type-erased so they can be used anywhere, but implementations are very much not. This does mean you will need to Vec<Box<dyn Widget>> in a bunch of places, but it's hard to avoid that for heterogenous UIs without a bunch of code-gen.