Reputation: 56
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> {
...
}
Upvotes: 1
Views: 1814
Reputation: 70870
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.
Upvotes: 1