Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

rust - How do I implement a trait with a generic method?

I'm trying to implement a trait which contains a generic method.

trait Trait {
    fn method<T>(&self) -> T;
}

struct Struct;

impl Trait for Struct {
    fn method(&self) -> u8 {
        return 16u8;
    }
}

I get:

error[E0049]: method `method` has 0 type parameters but its trait declaration has 1 type parameter
 --> src/lib.rs:8:5
  |
2 |     fn method<T>(&self) -> T;
  |     ------------------------- expected 1 type parameter
...
8 |     fn method(&self) -> u8 {
  |     ^^^^^^^^^^^^^^^^^^^^^^ found 0 type parameters

How should I write the impl block correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Type parameters in functions and methods are universal. This means that for all trait implementers, Trait::method<T> must be implemented for any T with the exact same constraints as those indicated by the trait (in this case, the constraint on T is only the implicit Sized).

The compiler's error message that you indicated suggests that it was still expecting the parameter type T. Instead, your Struct implementation is assuming that T = u8, which is incorrect. The type parameter is decided by the caller of the method rather than the implementer, so T might not always be u8.

If you wish to let the implementer choose a specific type, that has to be materialized in an associated type instead.

trait Trait {
    type Output;

    fn method(&self) -> Self::Output;
}

struct Struct;

impl Trait for Struct {
    type Output = u8;

    fn method(&self) -> u8 {
        16
    }
}

Read also this section of The Rust Programming Language: Specifying placeholder types in trait definitions with associated types.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...