码迷,mamicode.com
首页 > 其他好文 > 详细

interface _ golang

时间:2015-03-14 19:48:24      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:

Interfaces are named collections of methods signatures

package main

import (
    "fmt"
    "math"
)

type geometry interface {
    area() float64
    perim() float64
}

type square struct {
    width, height float64
}

type circle struct {
    radius float64
}

func (s square) area() float64 {
    return s.width * s.height
}

func (s square) perim() float64 {
    return 2*s.width + 2*s.height
}

func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}

func (c circle) perim() float64 {
    return 2 * math.Pi * c.radius
}

func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}

func main() {
    s := square{width: 3, height: 4}
    c := circle{radius: 5}

    measure(s)
    measure(c)
}
{3 4}
12
14
{5}
78.53981633974483
31.41592653589793

总结 :

  1 : interface ....没什么可说的....

  2 : 实现接口对应的所有方法

interface _ golang

标签:

原文地址:http://www.cnblogs.com/jackkiexu/p/4337960.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!