我希望能够向 struct 中添加两个同名的方法,它们将返回不同的数据类型.
struct NumParser<'a> {
splitting: Split<'a, &'a str>,
}
impl NumParser<'_> {
fn new<'a>(string: &'a str) -> NumParser<'a> {
NumParser{
splitting: string.trim().split(" "),
}
}
fn next(&mut self) -> u32 {
self.splitting.next().unwrap().parse().unwrap()
}
fn next(&mut self) -> u8 {
self.splitting.next().unwrap().parse().unwrap()
}
}
返回的类型将由注释或我为其赋值的变量的类型决定.
let mut parser: NumParser = NumParser::new(String::from("1 2 3 4 5"));
let var1: u32 = parser.next(); // the first next() would be called
let var2: u8 = parser.next(); // the second next() would be called
let arr: [u8; 2] = [parser.next(), parser.next()]; // both times the second next() would be called
var1 = parser.next(); // the first next() would be called, even without annotation
我try 使用特征,但似乎不能以这种方式实现两个同名的函数.