trait constraint on specific function rather than whole implementation

519 views Asked by At

I'm trying to implement a generic struct that can take any type parameter.

struct Position<T>{
    x: T,
    y: T,
}

impl<T:Num> Position<T>{
    fn add(&self, other: &Position<T>) -> Box<Position<T>>{
        box Position{x:self.x + other.x, y:self.y + other.y}
    }

    fn display(&self) -> String{
        "WELCOME ".to_string()
    }
}

now I can define

let original_position = Position::<int>{x: 2, y:23};
let another_postion   = original_position.add(&original_position);
let welcome           = original_postion.display();

without any error

similarly, i can do the following without any error.

let string_position = Position::<String>{x: "x_pos".to_string(), y: "y_pos".to_string()};

now due to the Num trait constraint i cannot call the following (which is obvious ).

string_position.add(&original_position);

but,my problem is that now i cannot call the following because of the same Num trait constraint

string_position.display()

the above function has noting to do with Num type, it simply returns the string "WELCOME"

how do i need to rewrite the implemetation so that add method can be called only by Position<Num> and display can be called by any other generic implementation.

1

There are 1 answers

1
Jorge Israel Peña On BEST ANSWER

You should create separate implementations, one with the bound and the other without, like this:

impl<T:Num> Position<T>{
    fn add(&self, other: &Position<T>) -> Box<Position<T>>{
        box Position{x:self.x + other.x, y:self.y + other.y}
    }
}

impl<T> Position<T>{
    fn display(&self) -> String{
        "WELCOME ".to_string()
    }
}

You can see that it works here.