如何在实现特征时避免函数名冲突?
How can I avoid a function name clash while implementing a trait?
我有一个结构,其实现具有访问结构私有状态的函数。
struct Example {...}
impl Example {
fn test(&self) -> .. {...}
}
另一个模块中的其他地方存在另一个特征:
trait ExampleTrait {
fn test(&self) -> .. {...}
}
现在我想为 Example
结构实现 ExampleTrait
并将测试方法转发给结构的测试 impl
。
以下代码:
impl ExampleTrait for Example {
fn test(&self) -> .. {
self.test()
}
}
显然是无限递归调用。我不能只重复原始测试的主体,因为我无法在此处访问 Example
的私有状态。
除了重命名一个函数或在 Example
public 中创建字段外,还有其他方法吗?
您可以使用 fully-qualified syntax 来区分要使用的方法:
impl ExampleTrait for Example {
fn test(&self) {
Example::test(self) // no more ambiguity
}
}
我有一个结构,其实现具有访问结构私有状态的函数。
struct Example {...}
impl Example {
fn test(&self) -> .. {...}
}
另一个模块中的其他地方存在另一个特征:
trait ExampleTrait {
fn test(&self) -> .. {...}
}
现在我想为 Example
结构实现 ExampleTrait
并将测试方法转发给结构的测试 impl
。
以下代码:
impl ExampleTrait for Example {
fn test(&self) -> .. {
self.test()
}
}
显然是无限递归调用。我不能只重复原始测试的主体,因为我无法在此处访问 Example
的私有状态。
除了重命名一个函数或在 Example
public 中创建字段外,还有其他方法吗?
您可以使用 fully-qualified syntax 来区分要使用的方法:
impl ExampleTrait for Example {
fn test(&self) {
Example::test(self) // no more ambiguity
}
}