# 09 Apr 2016 go语言接口学习

```type error interface {
Error() string
}```

go语言提供了一种接口类型interface，通过接口可以实现面向对象中一些特性，例如多态。go的接口只是一组方法的声明，抽象的定了对象的行为，并不具体实现。例如：

```type Shaper interface {
Area() int
Perimeter() int
}```

go语言中的接口都很简短，通常它们会包含0个、最多3个方法。这里定义了一个接口类型Shaper，并声明了2个方法Area()和Perimeter()，但是未给出Area()和Perimeter()方法的具体实现。如果某个类型实现了Area()和Perimeter()方法，就可以说该类型实现了Shaper接口，于是可以将该类型的实例赋值给Shaper类型变量。例如：

```type Square struct {
a int
}

func (s *Square) Area() int {
return s.a * s.a
}

func (s *Square) Perimeter() int {
return s.a * 4
}

square := new(Square)
square.a = 3

var shape Shaper
shape = square```

```type AnyShape interface{}
var anyShape AnyShape
anyShape = square```

```package main

import (
"fmt"
)

type Square struct {
a int
}

func (s *Square) Area() int {
return s.a * s.a
}

func (s *Square) Perimeter() int {
return s.a * 4
}

type Rectangle struct {
a int
b int
}

func (r *Rectangle) Area() int {
return r.a * r.b
}

func (r *Rectangle) Perimeter() int {
return (r.a + r.b) * 2
}

type RightTriangle struct {
a int
b int
// c is hypotenuse
c int
}

func (r *RightTriangle) Area() int {
return r.a * r.b / 2
}

func (r *RightTriangle) Perimeter() int {
return r.a + r.b + r.c
}

type Shaper interface {
Area() int
Perimeter() int
}

type AnyShape interface{}

func main() {

square := new(Square)
square.a = 12

rectangle := new(Rectangle)
rectangle.a = 12
rectangle.b = 5

rightTriangle := new(RightTriangle)
rightTriangle.a = 3
rightTriangle.b = 4
rightTriangle.c = 5

fmt.Println("(1) call struct method:")
fmt.Println("square area is: ", square.Area())
fmt.Println("rectangle area is: ", rectangle.Area())
fmt.Println("right triangle area is: ", rightTriangle.Area())

fmt.Println("\n(2) via interface:")
var shape Shaper
shape = square
fmt.Println("square area is: ", shape.Area())
shape = rectangle
fmt.Println("rectangle area is: ", shape.Area())
shape = rightTriangle
fmt.Println("right triangle area is: ", shape.Area())

fmt.Println("\n(3) via empty interface:")
var anyShape AnyShape
anyShape = square
fmt.Println("square area is: ", anyShape.(*Square).Area())
anyShape = rectangle
fmt.Println("rectangle area is: ", anyShape.(*Rectangle).Area())
anyShape = rightTriangle
fmt.Println("right triangle area is: ", anyShape.(*RightTriangle).Area())

fmt.Println("\n(4) type assertions via switch:")
switch shape := anyShape.(type) {
case *RightTriangle:
fmt.Printf("shape type is: %T\n", shape)
fmt.Println("rectangle area is: ", shape.Area())
default:
fmt.Printf("unknown type %T\n", shape)
}

fmt.Println("\n(5) type assertions via comma, ok pattern:")
anyShape = rectangle
if shape, ok := anyShape.(*Rectangle); ok {
fmt.Printf("shape type is: %T\n", shape)
fmt.Println("rectangle area is: ", shape.Area())
} else {
fmt.Printf("unknown type %T\n", shape)
}
}```

```(1) call struct method:
square area is:  144
rectangle area is:  60
right triangle area is:  6

(2) via interface:
square area is:  144
rectangle area is:  60
right triangle area is:  6

(3) via empty interface:
square area is:  144
rectangle area is:  60
right triangle area is:  6

(4) type assertions via switch:
shape type is: *main.RightTriangle
rectangle area is:  6

(5) type assertions via comma, ok pattern:
shape type is: *main.Rectangle
rectangle area is:  60```

《the way to go》

LEo at 23:40

69 篇文章30 人订阅

0 条评论

## 相关文章

### JavaScript_note1

4.6.字符串运算符 字符串运算符是用于两个字符型数据之间的运算符，除了比较运算符之外，还可以是+和+=运算符。 Demo：

972

3146

1602

2159

### 《Objective-C基础教程》笔记

1.xcode中，oc的.m文件代表message，指的是Objective-C的一个主要特性。 2.NS前缀的来历要追溯到次公局包还被成为NextStep，...

792

### Python3编程技巧

Microsoft Excel是Microsoft为使用Windows和Apple Macintosh操作系统的计算机编写的一款电子表格软件。直观的界面、出色的...

1022

### Go 语言简介（上）— 语法

Hello World package main //声明本文件的package名 import "fmt" //import语言的fmt库——用于输出 f...

3978

4287

3288

2229