首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在书中的代码示例11.1中使用接口?

如何在书中的代码示例11.1中使用接口?
EN

Stack Overflow用户
提问于 2015-06-04 03:24:33
回答 1查看 47关注 0票数 1

我正在学习Go,并试图充分理解如何在Go中使用接口。

在“前进之路”一书中,有一个例子列出了11.1 (第264-265页)。我觉得在我对它的理解中,我确实遗漏了一些东西。代码运行良好,但我不明白接口对结构和方法有什么影响(如果有的话)。

代码语言:javascript
复制
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())

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-04 04:05:22

在这个例子中,它没有任何效果。

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

下面是一个修改后的示例

注意printIt函数,它可以采取任何类型的依附于Shaper接口。

如果没有接口,您就必须创建printCircle和printRectangle方法,随着时间的推移,随着时间的推移,这些方法并不能真正工作,因为您向应用程序添加了越来越多的类型。

代码语言:javascript
复制
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())
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30634412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档