努力查看接口类型的用途 [英] Struggling to See the Purpose of an Interface Type
问题描述
我最近很喜欢Go编程语言,到目前为止,我发现它很棒,但是确实很难理解接口.我已经阅读了很多有关它们的内容,但是对我来说它们仍然很抽象.
I've recently taken a liking to the Go programming language, I've found it wonderful so far but am really struggling to understand interfaces. I've read about quite a bit about them, but they still seem very abstract to me.
我编写了一些使用下面的接口的快速代码:
I've wrote a quick bit of code that uses an interface below:
package main
import (
"fmt"
"math"
)
type Circer interface {
Circ() float64
}
type Square struct {
side float64
}
type Circle struct {
diam, rad float64
}
func (s *Square) Circ() float64 {
return s.side * 4
}
func (c *Circle) Circ() float64 {
return c.diam * math.Pi
}
func (c *Circle) Area() float64 {
if c.rad == 0 {
var rad = c.diam / 2
return (rad*rad) * math.Pi
} else {
return (c.rad*c.rad) * math.Pi
}
}
func main() {
var s = new(Square)
var c = new(Circle)
s.side = 2
c.diam = 10
var i Circer = s
fmt.Println("Square Circ: ", i.Circ())
i = c
fmt.Println("Circle Circ: ", i.Circ())
}
我真的看不到Circer界面的用途.这些方法已经编写好了,我可以通过直接在结构上直接调用它们而不是使用Circer作为包装器来保存两行代码.
I can't really see the purpose of the Circer interface. The methods are already written and I could save two lines of code by simply calling them directly on the structs, rather than using Circer as a wrapper.
有什么我想念的吗?我使用接口不正确吗?任何帮助或示例,不胜感激.
Is there something I'm missing? Am I using the interface incorrectly? Any help or examples are appreciated.
推荐答案
接口的要点是,您可以创建通用功能,例如下面的ShowMeTheCircumference
.
The point of interfaces is that you can make general purpose functions like ShowMeTheCircumference
below.
package main
import (
"fmt"
"math"
)
type Circer interface {
Circ() float64
}
type Square struct {
side float64
}
type Circle struct {
diam, rad float64
}
func (s *Square) Circ() float64 {
return s.side * 4
}
func (c *Circle) Circ() float64 {
return c.diam * math.Pi
}
func ShowMeTheCircumference(name string, shape Circer) {
fmt.Printf("Circumference of %s is %f\n", name, shape.Circ())
}
func main() {
square := &Square{side: 2}
circle := &Circle{diam: 10}
ShowMeTheCircumference("square", square)
ShowMeTheCircumference("circle", circle)
}
这篇关于努力查看接口类型的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!