取自 go tour:package mainimport ( "fmt" "math")type Abser interface { Abs() float64}func main() { var a Abser f := MyFloat(-math.Sqrt2) v := Vertex{3, 4} a = f a = &v // v == Vertex != *Vertex -> exception a = v}type MyFloat float64func (f MyFloat) Abs() float64 { if f < 0 { return float64(-f) } return float64(f)}type Vertex struct { X, Y float64}func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y)}但是,当func (v *Vertex) Abs() float64变成 时func (v Vertex) Abs() float64,代码编译:package mainimport ( "math")type Abser interface { Abs() float64}func main() { var a Abser f := MyFloat(-math.Sqrt2) v := Vertex{3, 4} a = f // Since *Vertex != Vertex, this shouldn't compile, should it? a = &v a = v}type MyFloat float64func (f MyFloat) Abs() float64 { if f < 0 { return float64(-f) } return float64(f)}type Vertex struct { X, Y float64}func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y)}为什么第二个例子会运行?
- 1 回答
- 0 关注
- 202 浏览
添加回答
举报
0/150
提交
取消