0

I want to call a non-generic private associated function from a non-generic method of a generic struct. I can't do that because Rust cannot infer the type parameter:

use std::fmt::Display;

struct MyStruct<T: Display> {
    val: T,
}

impl<T: Display> MyStruct<T> {
    pub fn show(&self) {
        MyStruct::label();
        println!("{}", self.val);
    }

    fn label() {
        print!("val: ");
    }
}

fn main() {
    let x = 42;
    let ms = MyStruct { val: x };
    ms.show();
}

Compiling this code gives an error:

error[E0282]: type annotations needed
 --> src/main.rs:9:9
  |
9 |         MyStruct::label();
  |         ^^^^^^^^^^^^^^^ cannot infer type for type parameter `T`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Piotr
  • 91
  • 1
  • 4
  • 1
    `MyStruct::::label();`, or just `Self::label();` See also: https://stackoverflow.com/questions/41017140 – E_net4 Nov 20 '20 at 17:08
  • Note that you can _also_ move the `fn label()` into another `impl` that is generic over `T` but has no bounds on `Display`, since any `MyStruct` (including those that are not `Display`) can use it. – user2722968 Nov 20 '20 at 17:33
  • Note that while @user2722968's advice is good, you'd _still_ have to specify a `T` to call it since the struct itself is generic. See also [Should trait bounds be duplicated in struct and impl?](https://stackoverflow.com/q/49229332/155423). – Shepmaster Nov 20 '20 at 17:52

0 Answers0