# go的非侵入式接口

bigtom · · 1505 次点击 · · 开始浏览

## 什么是接口

``````type Geometry interface {
Area() float64
Perim() float64
}

type Rect struct {
Width, Height float64
}

type Circle struct {
}

func (r Rect) Area() float64 {
return r.Width * r.Height
}

func (r Rect) Perim() float64 {
return 2 * (r.Width + r.Height)
}

func (c Circle) Area() float64 {
}

func (c Circle) Perim() float64 {
return math.Pi * c.Radius * 2
}``````

## 什么叫非侵入式接口

``````public interface Geometry {
public float Area();
}

public class Rect implements Geometry {
...
@override
public float Area(){
....
}
}``````

``````func Measure(g Geometry) {
fmt.Println(g)
fmt.Println(g.Area())
fmt.Println(g.Perim())
}

r := Rect{3,5}
c := Circle{4}
Measure(r)
Measure(c)``````

## 非侵入式接口的好处

2 回复  |  直到 1999-12-31 16:00:00

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

## 什么是接口

``````type Geometry interface {
Area() float64
Perim() float64
}

type Rect struct {
Width, Height float64
}

type Circle struct {
}

func (r Rect) Area() float64 {
return r.Width * r.Height
}

func (r Rect) Perim() float64 {
return 2 * (r.Width + r.Height)
}

func (c Circle) Area() float64 {
}

func (c Circle) Perim() float64 {
return math.Pi * c.Radius * 2
}``````

## 什么叫非侵入式接口

``````public interface Geometry {
public float Area();
}

public class Rect implements Geometry {
...
@override
public float Area(){
....
}
}``````

``````func Measure(g Geometry) {
fmt.Println(g)
fmt.Println(g.Area())
fmt.Println(g.Perim())
}

r := Rect{3,5}
c := Circle{4}
Measure(r)
Measure(c)``````