简体   繁体   中英

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.

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> {

...

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM