【问题标题】:Interface vs pointer/value receiver接口与指针/值接收器
【发布时间】:2020-10-01 04:04:37
【问题描述】:

如果我使用指针接收器,下面的代码在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=va=&v 都有效,这是什么原因?

【问题讨论】:

标签: go


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2018-01-20
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多