dsg56465 2015-06-04 03:24
浏览 31
已采纳

《 The Way to Go》一书的代码示例11.1中如何使用接口?

I am learning Go and am trying to fully understand how to use interfaces in Go.

In the book The Way to Go, there is an example listing 11.1 (pages 264-265). I feel that I am definitely missing something in my understanding of it. The code runs fine, but I do not understand what effect (if any) the interface is having on the struct and method.

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
", areaIntf.Area())

}
  • 写回答

1条回答 默认 最新

  • dq05304 2015-06-04 04:05
    关注

    In that example, it has no effect.

    Interfaces allow different types to adhere to a common contract, allowing you to create generalized functions.

    Here's a modified example on Play

    Notice the printIt function, it can take any type that adheres to the Shaper interface.

    Without interfaces, you would have had to make printCircle and printRectangle methods, which doesn't really work as you add more and more types to your application over time.

    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
    ", areaIntf.Area())
        areaIntf = circ1
        fmt.Printf("The circle has area: %f
    ", 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
    ", s.Area())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试