Interface 本书代码示例11.1中的接口是如何使用的?

Interface 本书代码示例11.1中的接口是如何使用的?,interface,go,Interface,Go,我正在学习围棋,并试图完全理解如何在围棋中使用界面 在《TheWayToGo》一书中,有一个示例清单11.1(第264-265页)。我觉得在我对它的理解中,我确实遗漏了一些东西。代码运行良好,但我不理解接口对结构和方法有什么影响(如果有) package main import "fmt" type Shaper interface { Area() float32 } type Square struct { side float32 } func (sq *Squar

我正在学习围棋,并试图完全理解如何在围棋中使用界面

在《TheWayToGo》一书中,有一个示例清单11.1(第264-265页)。我觉得在我对它的理解中,我确实遗漏了一些东西。代码运行良好,但我不理解接口对结构和方法有什么影响(如果有)

package main
import "fmt"


type Shaper interface {
    Area() float32
}

type Square struct {
    side float32
}

func (sq *Square) Area() float32 {
         return sq.side * sq.side
}

func main() {
    sq1 := new(Square)
    sq1.side = 5
    // var areaIntf Shaper
    // areaIntf = sq1
    // shorter, without separate declaration:
    // areaIntf := Shaper(sq1)
    // or even:
    areaIntf := sq1
    fmt.Printf("The square has area: %f\n", areaIntf.Area())

}

在那个例子中,它没有效果

接口允许不同类型遵守公共契约,从而允许您创建通用函数

下面是一个关于

请注意printIt函数,它可以采用与Shaper接口相一致的任何类型

如果没有接口,您将不得不 printCircle和printRectangle方法,随着时间的推移,向应用程序中添加越来越多的类型,这些方法实际上不起作用

package main

import (
    "fmt"
    "math"
)

type Shaper interface {
    Area() float32
}

type Square struct {
    side float32
}

func (sq *Square) Area() float32 {
    return sq.side * sq.side
}

type Circle struct {
    radius float32
}

func (c *Circle) Area() float32 {
    return math.Pi * c.radius * c.radius
}

func main() {
    sq1 := new(Square)
    sq1.side = 5
    circ1 := new(Circle)
    circ1.radius = 5
    var areaIntf Shaper
    areaIntf = sq1
    // areaIntf = sq1
    // shorter, without separate declaration:
    // areaIntf := Shaper(sq1)
    // or even:
    fmt.Printf("The square has area: %f\n", areaIntf.Area())
    areaIntf = circ1
    fmt.Printf("The circle has area: %f\n", areaIntf.Area())

    // Here is where interfaces are actually interesting
    printIt(sq1)
    printIt(circ1)
}

func printIt(s Shaper) {
    fmt.Printf("Area of this thing is: %f\n", s.Area())
}

areaIntf:=sq1
areaIntf:=shapper(sq1)
不同。在前者中,
区域intf
的类型为
*正方形
,在后者中为
整形器
。整形器可能更好地称为“曲面”,因为它只有一个“面积”方法。对我来说,塑造者应该是塑造的东西(即有一种叫做塑造的方法)。谢谢。这帮了大忙。我猜这只是书中的一个错误。