[英]Rust trait return type (Result)
This function creates a line segment by parsing the string defining the line segment.此 function 通过解析定义线段的字符串来创建线段。
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?我可以避免在特征中使用 generics 吗?
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> {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.