2

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?

1 Answer 1

1

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
    }
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.