# 4.5.3-2b 方法与属性查找

在两种情况下我们需要对目标类型进行属性、方法查找：&#x20;

1. 当编译器遇到形如`X.sel`的表达式时，其中`sel`可能是属性名，也可能是方法名&#x20;
2. 判断目标类型是否实现了某接口时，需要判断目标类型是否包含对应接口的所有方法

整个查找逻辑定义在文件`$GCROOT/compile/internal/types2/lookup.go`文件中，入口方法是`lookupFieldOrMethod()` 。Go 不允许方法重载（Method Overloading），并且属性与方法也能重名，所以对属性、方法查找的基本思路很简单，就是按照名字匹配就可以了。虽然如此，属性查找的逻辑仍然有一些点值得讨论：

### 内嵌类型属性的二义性检测

如果在类型中有重复的命名，不用等到属性查找阶段，编译器在对类型申明进行类型检查时就会发现错误，例如：

```go
  type A struct {
      name string
      name string // Compile error: name redeclared [DuplicateDecl]
  }

  func (this *A) name() {} // Compile error: Field and method with the same name name [DuplicateFieldAndMethod]
```

但我们知道对于内嵌类型，Go 会提升（Promote）内嵌类型的属性，例如：

```go
  type A struct {
      Name string
  }
  type B struct {
      A
      Addr string
  }

  func main() {
      var b B
      name := b.Name // 直接访问内嵌类型的字段
      addr := b.Addr
  }
```

但上述代码中 Go 并不会真的将 A 的属性 Name 抽取出来放入类型 B 中，这种“提升”其实只是一种便捷的访问方式，在对属性的查找过程中实现：如果当前类型的属性没有匹配项，则对下一级的内嵌类型进行查找，并依此逻辑递归直到查找完所有内嵌类型。这时便会面临一个问题：如果同一层级的内嵌类型有相同属性，那么编译器就不知道到底应该使用哪一个。例如代码：

```go
  type A struct {
      Name string
  }
  type B struct {
      Name string
  }
  type C struct {
      A
      B
  }

  func main() {
      var b B
      name := b.Name // Compile error: ambigous selector b.Name [AmbigousSelector]
  }
```

此时编译器会提示错误，从而引导用户提供更明确的选择，例如：`b.A.Name`

### 方法的等价性校验

方法`missingMethod(V Type, T Interface, static bool) (method, wrongType Func)`用来判断类型V是否实现了接口T，如果返回值为 nil, 则 V 实现了接口 T; 否则返回值表示查找到的第一个 V 没有实现 T 的方法。

这里涉及到的逻辑分为两个部分：一是对于 T 中的每个方法，按照方法名在 V 中进行查找；二是如果在 V 中找到了同名方法的话，判断两个方法是否是同一个类型，即判断是否拥有一致的参数列表与返回值列表。第一部分的思路与属性的查找一致；第二部分为了支持泛型，在此处并没有使用[类型的等价规则](/golang-bian-yi-qi-lei-xing-jian-cha/4.4.412-lei-xing-de-deng-jia-gui-ze-fl.md)中的等价比较算法，这里叫着类型统一（[Type unification](https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#type-unification)），当前的实现逻辑在文件`$GCROOT/compile/internal/types2/unify.go`中，入口方法是`func (u *unifier) unify(x, y Type) bool {}`为什么叫类型统一呢？如果将类型想象成一个树形结构（或者图）的话，那么类型的等价规则的核心思想就是比较两个类型的结构是否一致，并且各对应结点的类型是否等价。这在没有类型参数的情况下是合理的，但是类型参数的引入使得该逻辑变得不够完善。在对[泛型数据结构](/golang-bian-yi-qi-lei-xing-jian-cha/4.4.411-fan-xing-lei-xing-fl.md)的讨论中我们提到过类型模版的概念，意在说明包含泛型申明的类型可以表示不同的实际类型，例如，假如 T1 与 T2 都是类型参数，那么一个实际类型`map[int]bool`可以用如下类型来表示：

* T1 (T1 匹配 map\[int]bool, 或者直接用 T2 也可以)
* map\[T1]bool (T1 匹配 int)
* map\[int]T2 （T2 匹配 bool）
* map\[T1]T2 (T1 匹配 int, T2 匹配 bool)

  反过来，其无法被下述类型表示：
* \[]T1
* struct{}
* map\[T1]string

可见当引入类型参数后，在结构上不同的两个类型也可能是一个类型，所以此时的处理思路不再是一一对比，而是尝试着找到某种方法来将两个类型统一成同一个类型，从代数上理解的话，有点像寻找两个类型的公倍数。所以从实现上来说，该部分的逻辑如下：撇开类型参数，两个类型结构上必须一致，并且类型必须等价；如果有类型参数的话，那么一个类型的类型参数能够匹配另一个类型的类型参数的所有子类型。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gocompiler.shizhz.me/golang-bian-yi-qi-lei-xing-jian-cha/4.5.32b-fang-fa-yu-shu-xing-cha-zhao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
