In code below, I am trying to implement a generic struct. What I want to achieve is, for T whose type is String, print self.x
value, and for all other types, print both self.x
and self.y
.
This question is not relevant to trait
, I only tried to impl
functions for a struct.
use core::fmt::Display;
use core::fmt::Debug;
#[derive(Debug)]
struct Point<T> {
x: T,
y: T
}
impl Point<String> {
fn print(&self) {
println!("{:?}", self.x);
}
}
impl<T: Display + Debug> Point<T> {
fn print(&self) {
println!("{:?}", self.x);
println!("{:?}", self.y);
}
}
fn main() {
let x = Point{x: String::from("123"), y: String::from("456")};
let y = Point{x: 123, y: 456};
//let z = Point{x: vec![1,2,3], y: vec![4,5,6]};
x.print();
y.print();
//z.print();
}
However, I got the compile error below:
error[E0592]: duplicate definitions with name `print`
What is the correct way to achieve it?
Moreover, I also tried to use vectors as x and y(the z
in main), which is not allow, I want to know the reason.