【发布时间】: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=v 和 a=&v 都有效,这是什么原因?
【问题讨论】:
-
两个功能一样吗?
-
@william007 我正在寻找合适的资源来标记这里
标签: go