为什么在具体实现中使用Self代替类型名称?

问题描述 投票:0回答:1

The documentation for Add给出以下示例:

Add

为什么文档作者在这里使用use std::ops::Add; #[derive(Debug, PartialEq)] struct Point { x: i32, y: i32, } impl Add for Point { type Output = Self; fn add(self, other: Self) -> Self { Self { x: self.x + other.x, y: self.y + other.y, } } } ,而不是用名字提及Self?有技术上的区别,还是纯粹是风格方面的区别?

rust traits self-type
1个回答
0
投票

主要有两个原因:

  • 灵活性。如果您决定更改类型的名称,那么就不那么要更新了。
  • 简洁。 PointSelfMyType短,尤其是SomeOtherType

另请参见:

  • ThisTypeWithGenerics<'a, 'b, A, String>
© www.soinside.com 2019 - 2024. All rights reserved.