Reputation: 187
I just started fiddling with Rust and I found an error I don't understand, trying to build something like a DSL.
I've defined a struct like this:
struct Thing<T> {
a: T
}
impl<T: Show> Thing<T> {
fn selfie<T>(&self) -> Thing<T> { Thing { a: self.a } }
fn say<T>(&self) { println!("sing") }
}
Then I call it like this and get the error:
let a = Thing { a: 1i }; // works
a.say(); // works
let s = a.selfie(); //works
s.say(); // error
main.rs:49:5: 49:12 error: cannot determine a type for this bounded type parameter: unconstrained type
main.rs:49 s.say();
^~~~~~~
Does anyone know what this error means? I'm having a hard time figuring it out, and have tried a few different casts and nothing seems to work.
Alternatively, is there a better way to return a reference to "self" (which is what I really wanted to do in the "selfie" method but I was getting errors due to the reference lifespan) or to "an equivalent struct of the same kind"?
Upvotes: 1
Views: 378
Reputation: 16630
This compiles with a recent Rust version.
use std::fmt::Show;
struct Thing<T> {
a: T
}
impl<T: Show + Clone> Thing<T> {
fn selfie(&self) -> Thing<T> { Thing { a: self.a.clone() } }
fn say(&self) { println!("sing: {}", self.a) }
}
I'm assuming that the say
method should actually print a
(because otherwise the Show bound makes no sense).
The problem was that in say<T>
a generic type T exists but cannot be inferred because it's not used. In the selfie method, the <T>
is not needed. We do need to restrict T to those types that implement Clone though if we want to clone it.
I should also point out that the selfie
method is reinventing clone
. You could just do:
#[deriving(Clone)]
struct Thing<T> {
a: T
}
and then call clone()
rather than selfie
.
Upvotes: 2