Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Static methods in traits #14582

Closed
Monnoroch opened this issue Jun 1, 2014 · 3 comments
Closed

Static methods in traits #14582

Monnoroch opened this issue Jun 1, 2014 · 3 comments

Comments

@Monnoroch
Copy link

Is this a bug or a feature?

trait MyTrait {
    fn act();
}

fn act<T:MyTrait>(val: &T) {
    T::act();
}

Gives:

main.rs:19:6: 19:12 error: unresolved name
main.rs:19      T::act();
                ^~~~~~
main.rs:19:6: 19:12 error: use of undeclared module `T`
main.rs:19      T::act();
                ^~~~~~
main.rs:19:6: 19:12 error: unresolved name `T::act`. Did you mean `val`?
main.rs:19      T::act();
@huonw
Copy link
Member

huonw commented Jun 1, 2014

This is a "feature" (well, a bug too, but it's well covered elsewhere, e.g. #6894). Static methods need to be called like MyTrait::act(). However, this doesn't allow the Self type to be infered correctly. The standard work around is using a dummy parameter that mentions Self. e.g.

trait MyTrait {
    fn act(_dummy: Option<Self>);
}

fn act<T: MyTrait>(val: &T) {
    MyTrait::act(None::<T>); // call T's act method
}

This precise behaviour is covered by "uniform function call syntax", which is being discussed in RFCs like rust-lang/rfcs#4.

(Thanks for filing.)

@huonw huonw closed this as completed Jun 1, 2014
@Monnoroch
Copy link
Author

Thanks for the answer!
But will it be fixed sometime? I mean, this workaround is really messy. It might be that i don't even own the MyTrait code, so i can't change it.

But my act actually returned Self, so i didn't even use this hack.

@huonw
Copy link
Member

huonw commented Jun 1, 2014

Yes, it will be fixed; the RFC I linked above is proposing a fix, but there is still some discussion happening in this area.

If you don't own MyTrait and the static methods don't have a workaround like this, then no-one can use them, not even the original library, i.e. the library is fundamentally broken.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants