我希望能够向 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 使用特征,但似乎不能以这种方式实现两个同名的函数.

推荐答案

尽管有两个支持相反的答案,但您可以定义一个返回类型为u8u32(或者实际上是您想要的任意数量的和类型)的方法.唯一需要注意的是,您不能将这些方法实现为NumParser的固有方法,而必须为它们创建一个特征,例如:

trait Next<T> {
    fn next(&mut self) -> T;
}

然后,您可以将返回类型不同的两个方法定义为您的 struct 的两个不同的特征实现:

impl Next<u32> for NumParser<'_> {
    fn next(&mut self) -> u32 {
        self.splitting.next().unwrap().parse().unwrap()
    }
}
impl Next<u8> for NumParser<'_> {
    fn next(&mut self) -> u8 {
        self.splitting.next().unwrap().parse().unwrap()
    }
}

或者,如果您希望为每T个可解析的对象实现它(实现FromStr个):

impl<T: std::str::FromStr> Next<T> for NumParser<'_>
where
    T::Err: Debug,
{
    fn next(&mut self) -> T {
        self.splitting.next().unwrap().parse().unwrap()
    }
}

Rust编译器将根据您需要的类型 Select 要调用的方法:

fn main() {
    let s = "12 34 56 78";
    let mut p = NumParser::new(s);
    let a: u8 = p.next();
    let b: u32 = p.next();
    dbg!(a, b);
}

Rust相关问答推荐

如何在rust中有条件地分配变量?

为什么std repeat trait绑定在impl块和关联函数之间?

新创建的变量的绑定生存期

如何循环遍历0..V.len()-1何时v可能为空?

如何go 除多余的(0..)在迭代中,当它不被使用时?

为什么Rust不支持带关联常量的特征对象?

Rust 文件未编译到 dll 中

Rust 中的 Option as_ref 和 as_deref 有什么不同

在不安全的 Rust 中存储对 struct 内部数据的静态引用是否合法?

如何在 Rust 中将枚举变体转换为 u8?

我什么时候应该使用特征作为 Rust 的类型?

不能将 `*self` borrow 为不可变的,因为它也被borrow 为可变的 - 编译器真的需要如此严格吗?

切片不能被 `usize` 索引?

将一片字节复制到一个大小不匹配的数组中

使用 HashMap 条目时如何避免字符串键的短暂克隆?

我如何将特征作为 struct 的拥有字段?

Rustfmt 是否有明确类型的选项?

为什么这个值在上次使用后没有下降?

Rust 为什么 (u32, u32) 的枚举变体的大小小于 (u64)?

为移动和借位的所有组合实现 Add、Sub、Mul、Div