关于接口的方法实现

Pei*_*ung 0 go

任何人都可以解释为什么调用a.Abs()有效吗?在我看来,'a'是*Vertex类型的变量,但*Vertex类型不实现Abs方法.

package main

import (
    "fmt"
    "math"
)

type Abser interface {
    Abs() float64
}

func main() {
    var a Abser

    v := Vertex{3, 4}
    a = &v // a *Vertex implements Abser
    // In the following line, v is a *Vertex (not Vertex)
    // and does NOT implement Abser, but why does this calling work?
    fmt.Println(a.Abs())

}

type Vertex struct {
    X, Y float64
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 5

精细规格:

方法集
[...]相应指针类型的方法集*T是用receiver*T或T声明的所有方法的集合(也就是说,它还包含T的方法集).[...]

你的Abs功能是在方法设置两个Vertex*Vertex因此*Vertex是一个Abser就像Vertex是.

其他相关部分:

通常,指针会在可能的情况下自动解除引用,因此您可以说x.M()并且x.V不必担心是否x是指针,并且不需要C ->或手动解除引用(即(*x).M()(*x).V).