Sho Ogihara
Sho Ogihara

Reputation: 281

rust struct with generics compile error

I wrote following code in rust. version is 0.12.0-pre-nightly.

struct Sample<T> {
    x: T
}

impl<T> Sample<T> {
    pub fn new<T>(v: T) -> Sample<T> {
        Sample { x: v }
    }

    pub fn get<T>(&self) -> T {
        self.x
    }
}

fn main() {
    Sample::new(0i).get(); // expect int 0
}

and got compile error.

hoge.rs:11:9: 11:15 error: mismatched types: expected `T`, found `T` (expected type parameter, found type parameter)
hoge.rs:11         self.x

I cannot figure out by compiler message why sample program cannot be compiled. How can I fix it?

Upvotes: 2

Views: 117

Answers (1)

Francis Gagn&#233;
Francis Gagn&#233;

Reputation: 65682

Don't put type parameters on your methods. They must use the one from the impl.

struct Sample<T> {
    x: T
}

impl<T> Sample<T> {
    pub fn new(v: T) -> Sample<T> {
        Sample { x: v }
    }

    pub fn get(&self) -> T {
        self.x
    }
}

fn main() {
    Sample::new(0i).get(); // expect int 0
}

P.S.: That code doesn't compile either because get tries to move x out of &self. You can change impl<T> to impl<T: Copy> if you want to use copyable types only, or change get to return a reference:

    pub fn get(&self) -> &T {
        &self.x
    }

Upvotes: 1

Related Questions