Trait vars

Hi all, I just wanted to suggest a new feature. A while back I suggested "impl vars", which I still believe has uses, but I think that "Trait vars" is much more useful still. This would allow default Trait methods to set / retrieve state, and would also give the struct that implemented that trait access to those 'Trait vars' on 'self', even outside the impl block (as long as it was impld, those Trait vars becomes part of self). So, like a "true mixin" (as I see it anyways - lots of different views on what a mixin is). I don't want to suggest much with regards to access modifiers and the exact meaning they'd take in this context. Just leaving as a high level concept to think about. Thoughts? Jeff

1 Like

Clarifying, you're talking about having a variable declared in a trait, such that it's expected to be a read-write field of any type implementing the trait?

I think my questions from the "impl vars" discussion still applies here.

If I impl TraitWithVar for Vec<u8>, where does the variable get stored on self? Is Vec<u8> now different for my crate than every other crate? How does this work with Vec::from_raw_parts which would now strip whatever "trait var" are there? What would the default value be? How about Vec::new() too?

Here is an idea. Not sure if it's a good one, but it's an idea.

Trait vars are implemented as methods that return a reference. Mutability complicates things, so let's ignore it for now, but I'm thinking something like:

trait Foo {
    trait_var bar(&self): u32;
}

struct Baz(u32);

impl Foo for Baz {
    trait_var bar(&self) {
        &self.0
    }
}

fn main() {
    let baz = Baz(42);
    let foo: &dyn Foo = &baz;
    assert!(foo.bar == 42);
}

But if you ignore mut support then it's just fn bar(&self) -> &u32 with different syntax.

3 Likes

It sounds like you want syntactic sugar for traits that "get/set" a value. Interestingly, many languages that provide something like interfaces with value properties end up shying away from using them in the end.

It's a bit of boilerplate, but you can already create these sorts of traits via methods.Ultimately, this lets implementors use a value directly or compute a value some other way using the same trait.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.