# Interface - 初探 Golang 中的接口（一）

#### 1. 类型行为的概括和抽象

``````package shape

import "fmt"

type AreaTeller interface {
Area() float64
}

func TellArea(at AreaTeller) {
fmt.Printf("Hello, my area is %.2f\n", at.Area())
}

``````

#### 2. 接口的调用和实现

``````type Rectangle struct {
X, Y float64
}

type Circle struct {
R float64
}
``````

``````package main

import (
"github.com/alienrick/00_test/area"
)

type Rectangle struct {
X, Y float64
}

type Circle struct {
R float64
}

func main() {
r := Rectangle{X: 3, Y: 4}
shape.TellArea(r) // error

c := Circle{R: 3}
shape.TellArea(c) // error
}

``````

``````func (r Rectangle) Area() float64 {
return r.X * r.Y
}

func (c Circle) Area() float64 {
return math.Pi * c.R * c.R
}
``````

``````package main

import (
"math"

"github.com/alienrick/00_test/shape"
)

type Rectangle struct {
X, Y float64
}

func (r Rectangle) Area() float64 {
return r.X * r.Y
}

func (c Circle) Area() float64 {
return math.Pi * c.R * c.R
}

type Circle struct {
R float64
}

func main() {
r := Rectangle{X: 3, Y: 4}
shape.TellArea(r)

c := Circle{R: 3}
shape.TellArea(c)
}

``````

``````Hello, my area is 12.00
Hello, my area is 28.27
``````

#### 3.扩展

``````type Square struct {
X float64
}

func (t Square) Area() float64 {
return t.X * t.X
}

func main(){
s := Square{X: 3}
shape.TellArea(s) // Hello, my area is 9.00
}
``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

#### 1. 类型行为的概括和抽象

``````package shape

import "fmt"

type AreaTeller interface {
Area() float64
}

func TellArea(at AreaTeller) {
fmt.Printf("Hello, my area is %.2f\n", at.Area())
}

``````

#### 2. 接口的调用和实现

``````type Rectangle struct {
X, Y float64
}

type Circle struct {
R float64
}
``````

``````package main

import (
"github.com/alienrick/00_test/area"
)

type Rectangle struct {
X, Y float64
}

type Circle struct {
R float64
}

func main() {
r := Rectangle{X: 3, Y: 4}
shape.TellArea(r) // error

c := Circle{R: 3}
shape.TellArea(c) // error
}

``````

``````func (r Rectangle) Area() float64 {
return r.X * r.Y
}

func (c Circle) Area() float64 {
return math.Pi * c.R * c.R
}
``````

``````package main

import (
"math"

"github.com/alienrick/00_test/shape"
)

type Rectangle struct {
X, Y float64
}

func (r Rectangle) Area() float64 {
return r.X * r.Y
}

func (c Circle) Area() float64 {
return math.Pi * c.R * c.R
}

type Circle struct {
R float64
}

func main() {
r := Rectangle{X: 3, Y: 4}
shape.TellArea(r)

c := Circle{R: 3}
shape.TellArea(c)
}

``````

``````Hello, my area is 12.00
Hello, my area is 28.27
``````

#### 3.扩展

``````type Square struct {
X float64
}

func (t Square) Area() float64 {
return t.X * t.X
}

func main(){
s := Square{X: 3}
shape.TellArea(s) // Hello, my area is 9.00
}
``````