Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust trait return type (Result)

This function creates a line segment by parsing the string defining the line segment.

Since there is an item to parse other than the line segment, I tried to use a trait.

I implemented it like below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pub trait GeomParser<T> {
    fn parse(str_line: &str) -> Result<T, std::num::ParseFloatError>;
}

impl GeomParser<Segment> for Segment {
    fn parse(str_line: &str) -> Result<Segment, std::num::ParseFloatError> {
        let mut strs_iter = str_line.split_ascii_whitespace();

        strs_iter.next(); // L
        let start_x : f64 = strs_iter.next().unwrap().parse()?;
        let start_y : f64 = strs_iter.next().unwrap().parse()?;
        let end_x : f64 = strs_iter.next().unwrap().parse()?;
        let end_y : f64 = strs_iter.next().unwrap().parse()?;
        let width : f64 = strs_iter.next().unwrap().parse()?;

        let seg = Segment
        {
            start : Point { x: start_x, y: start_y },
            end : Point { x: end_x, y: end_y },
            width : width,
        };

        Ok(seg)
    }
}

Can I avoid using generics in the trait?

I would like to specify the type of the struct you implement as the return type?

pub trait GeomParser {
    fn parse(str_line: &str) -> Result<????, std::num::ParseFloatError>;
}

impl GeomParser for Segment {
    fn parse(str_line: &str) -> Result<Segment, std::num::ParseFloatError> {

...

}

>Solution :

You’re looking for Self:

pub trait GeomParser: Sized {
    fn parse(str_line: &str) -> Result<Self, std::num::ParseFloatError>;
}

It is the type implementing the trait.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading