Trait implementation question

I'm learning Rust and while working on a small program came across this quirk with implementing traits.

I have a small one method trait that takes a string and returns a struct.

pub trait Deserialize {
    fn deserialize(&str) -> Self;
}

When I implement it for a simple struct Point{lat: f64, long: f64}

impl Deserialize for Point {
   fn deserialize(&str) -> Point { 
     ...
   }
}

I get an error "the size for values of type Self cannot be known at compilation time". I can get around it by changing the signature to fn deserialize(&str) -> Box<Self>.

However looking through some examples of Rust code I saw the following which works

pub trait Deserialize<T> {
    fn deserialize(&str) -> T {
      ...
    }
}

 impl Deserilize<Point> for Point {
    fn deserialize(&str) -> Point {
        ...
    }
}

I do not get the error and do not need to Box the result. Is there some disadvantage of using the second method for defining and implementing the trait? The first method using Self seems to be the one that is preferred in the documentation.

Can you please show the code with the error? I can't reproduce it.

This works just fine

struct Point { x: f32, y: f32 }

pub trait Deserialize {
    fn deserialize(s: &str) -> Self;
}

impl Deserialize for Point {
   fn deserialize(s: &str) -> Point { 
     unimplemented!()
   }
}

Not sure what I did but I got rid of the error while doing some refactoring. Guess I had some other issue.

I managed to recreate the error message, it was when I changed the signature to

fn deserialize(s: &str) -> Option<Self>;

I did some googling on that and it seemed that it's a pretty common issue.

This is because Option<T> requires that T is Sized, but in traits Self may not be sized. For example, dyn Deserialize is not Sized. This requires you to explicitly opt out of !Sized in deserialize or Deserialize using where Self: Sized or trait Deserialize: Sized { ... }.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.