-2

I've applied generics to a struct and want to get its output in an Option<_, _> type using a getter method implemented on the struct.

struct Point<T, U> {
    x: T,
    y: U,
}
impl<T, U> Point<T, U> {
    fn x(&self) -> Option<T, U> {
        let z = &self.x;
        z.get(5);
    }
}

fn main() {
    let p = Point { x: 5, y: 10.0 };
    println!("p.x = {}", p.x());
}

(Playground)

The output of the above mentioned code is

error[E0107]: wrong number of type arguments: expected 1, found 2
 --> src/main.rs:6:30
  |
6 |     fn x(&self) -> Option<T, U> {
  |                              ^ unexpected type argument
SuperStormer
  • 4,997
  • 5
  • 25
  • 35

1 Answers1

3

Take the time to read the documentation for the types you are using. Option only has one generic type:

pub enum Option<T> {
    None,
    Some(T),
}

As an educated guess, you likely meant to use a tuple:

fn x(&self) -> Option<(T, U)> {
    unimplemented!()
}

Other possibilities are Result:

fn x(&self) -> Result<T, U> {
    unimplemented!()
}

Or perhaps Either:

fn x(&self) -> either::Either<T, U> {
    unimplemented!()
}

See also:


Your code has a number of problems that will prevent it from compiling:

  • You cannot return owned T or U types in a method that takes &self without performing some kind of copying / cloning.
  • You cannot call a method (get) on a generic type without some kind of trait bounds. The method doesn't even seem to be defined.
  • You cannot format a tuple with the Display formatter.
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I think he actually wants `Either`. – Peter Hall Apr 07 '20 at 14:59
  • @JohnKugelman indeed! Since `get` isn't defined, it's even harder to guess. – Shepmaster Apr 07 '20 at 14:59
  • @Shepmaster Is there any method named get() in rust prelude? – Fawad Ahmed Apr 07 '20 at 15:23
  • @FawadAhmed you can see [all the methods in the Rust standard library named `get`](https://doc.rust-lang.org/std/?search=get) and the contents of [the prelude](https://doc.rust-lang.org/std/prelude/index.html) . That being said, **you** wrote this code, so shouldn't **you** know what that `get` is supposed to be? – Shepmaster Apr 07 '20 at 15:31
  • @Shepmaster That is what I'm confused with. Thanks for correcting me. – Fawad Ahmed Apr 07 '20 at 15:39