Go 接口与指针/值接收器

Go 接口与指针/值接收器,go,Go,如果我使用指针接收器,下面的代码在a=v处有异常,因为它是在指针v上定义的,所以它是有意义的 package main import ( "fmt" "math" ) type Abser interface { Abs(x int) float64 //all types needs to implement this interface } type Vertex struct { X float64 } func

如果我使用指针接收器,下面的代码在
a=v
处有异常,因为它是在指针v上定义的,所以它是有意义的

package main
import (
    "fmt"
    "math"
)

type Abser interface {
    Abs(x int) float64 //all types needs to implement this interface
}

type Vertex struct {
    X float64
}

func (v *Vertex) Abs(x int) float64 {
    return math.Abs(float64(x))
}


func main() {

    /*define the interface and assign to it*/
    var a Abser
    v := Vertex{-3}
    a = &v
    fmt.Println(a.Abs(-3))

    a = v
    fmt.Println(a.Abs(-3))
}
但是如果我把Abs的功能改为

func (v Vertex) Abs(x int) float64 {
    return math.Abs(float64(x))
}

a=v
a=&v
都有效,这背后的原因是什么?

这样理解它,因为我没有合适的资源来引用;当接口在值上实现时,Go很乐意将指针结构的副本作为值传递,您可以通过打印变量的地址来检查这一点;这是因为该操作被认为是安全的,不能改变原始值

这两个函数都是一样的?@william007我正在寻找合适的资源来标记hereDo,回答你的问题:,这回答了你的问题吗?