2

Can a non-generic struct implement a generic function in rust, which works like:


struct S;

impl <T> S {
    fn do_something(value : T) {
        //do something
    }
}

fn main() {
    let a = /*a value*/;
    S::do_something(a);
}

If not, assuming S implement a generic trait Tt:


struct S;

impl <T> Tt<T> for S {
    fn a_func(value : T) {
        //do something
    }
}

impl <T> S {
    fn do_something(value : T) {
        //do something
    }
}

fn main() {
    let a = /*a value*/;
    S::do_something(a);
}

Is there any way to make it works?

1
  • how about defining generic parameter for fn instead of struct ? Commented Jul 4, 2019 at 15:41

1 Answer 1

1

You can only declare a type variable for an impl block if it is used in the type itself.

However, you can introduce new type variables on individual methods too:

impl S {
    fn do_something<T>(value: T) {
        //do something
    }
}

This is particularly common for arguments that are closures, because every closure has a different type, so this is necessary for you to be able to call the method with a different closure each time. For example, Iterator::map is defined like this:

fn map<B, F>(self, f: F) -> Map<Self, F>
where
    F: FnMut(Self::Item) -> B, 

If the F was declared for the type instead of the method then you would have to use the same closure every time you call map - not very useful.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.