Introduction
In this lab, we learn how to implement generic types and methods in Rust, allowing us to specify different type parameters when using the struct or calling the methods.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
Implementation
Similar to functions, implementations require care to remain generic.
struct S; // Concrete type `S`
struct GenericVal<T>(T); // Generic type `GenericVal`
// impl of GenericVal where we explicitly specify type parameters:
impl GenericVal<f32> {} // Specify `f32`
impl GenericVal<S> {} // Specify `S` as defined above
// `<T>` Must precede the type to remain generic
impl<T> GenericVal<T> {}
struct Val {
val: f64,
}
struct GenVal<T> {
gen_val: T,
}
// impl of Val
impl Val {
fn value(&self) -> &f64 {
&self.val
}
}
// impl of GenVal for a generic type `T`
impl<T> GenVal<T> {
fn value(&self) -> &T {
&self.gen_val
}
}
fn main() {
let x = Val { val: 3.0 };
let y = GenVal { gen_val: 3i32 };
println!("{}, {}", x.value(), y.value());
}
Summary
Congratulations! You have completed the Implementation lab. You can practice more labs in LabEx to improve your skills.