danixl30 ct
danixl30 ct

Reputation: 145

Try to compare generic types

I am trying to implement a linked list in rust, I use the generic type T, but I want to compare two numbers, but I can not because the generic T does not allow to compare using integer methods. This is my code:

`

pub struct List<T> {
    head: Link<T>
}

type Link<T> = Option<Box<Node<T>>>;

struct Node<T> {
    value: T,
    next: Link<T>
}

impl<T> Node <T> 
{
    fn new(value: T, next: Link<T>) -> Self {
        Node {value: value, next: next}
    }
    
    fn check_and_put(&mut self, value: T) 
    {
        if (self.next.is_none()) {
            self.next = Some(Box::new(Node::new(value, None))); 
        }else {
            if (compare(value, self.value)) {
                self.next = Some(Box::new(Node::new(value, self.next)));
            }
            self.next.as_mut().map(|nod| {
                nod.check_and_put(value);
            });
        }
    }
}

impl<T> List<T> {
    fn new() -> Self {
        List {head: None}
    }
    
    fn add_element(&mut self, value: T) {
        if (!self.head.is_none()){
            self.head.as_mut().map(|node| {
                node.check_and_put(value);
            });
        }else {
            self.head = Some(Box::new(Node::new(value, None)));
        }
    }
}

fn compare(a: i32, b: i32) -> bool {
    if (a > b){
        true
    }else {
        false
    }
}

fn main() {
    let mut list = List::new();
    list.add_element(1);
    list.add_element(2);
    list.add_element(1);
}

`

This is the error:

error[E0308]: mismatched types


--> single-list.rs:24:25
   |
13 | impl<T> Node <T>
   |      - this type parameter
...
24 |             if (compare(value, self.value)) {
   |                         ^^^^^ expected `i32`, found type parameter `T`
   |
   = note:        expected type `i32`
           found type parameter `T`

I am not very good with english and this is my first question, I hope that you can understand me.

Upvotes: 2

Views: 2599

Answers (1)

Netwave
Netwave

Reputation: 42786

You need to bind your types with some constrains in order to do that:

fn compare<T: Ord>(a: &T, b: &T) -> bool {
    if a > b{
        true
    }else {
        false
    }
}

As well as:

impl<T: Ord> Node <T> {
...
}

impl<T: Ord> List<T> {
...
}

After this you will encounter other problems. Your implementation will not work (due to ownership problems).

Playground

Upvotes: 2

Related Questions