Hi people!
How can a structure be used as a template parameter?
The following code will not compile.
struct Point {
x: f64,
y: f64,
}
impl Point {
fn new() -> Self {
Self {x: 0., y: 0.}
}
}
struct User {
point: T,
}
impl User {
fn new() -> Self {
Self { point: T::new() }
}
}
How to solve this problem?
SDX
October 15, 2021, 9:05am
2
Traits. Your code will not compile because there's nothing telling the compiler that the type T
you're using in your User
struct has the new
method. It's solved quite simply:
trait Usable {
fn new() -> Self;
}
impl Usable for Point {
fn new() -> Self {
// your impl
}
}
struct User<T: Usable> {
thing: T
}
impl<T: Usable> User<T> {
fn new() -> {
Self { thing: T::new() }
}
}
1 Like
Thank you very much for your prompt response!
1 Like
kornel
October 15, 2021, 11:29am
4
BTW, in this case there's an existing Default
trait.
2 Likes
system
Closed
January 13, 2022, 11:29am
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.