go编程提供了另一种称为接口(interfaces
)的数据类型,它代表一组方法签名。struct
数据类型实现这些接口以具有接口的方法签名的方法定义。
/* define an interface */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
/* define a struct */
type struct_name struct {
/* variables */
}
/* implement interface methods*/
func (struct_name_variable struct_name) method_name1() [return_type] {
/* method implementation */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
/* method implementation */
}
package main
import (
"fmt"
"math"
)
/* define an interface */
type shape interface {
area() float64
}
/* define a circle */
type circle struct {
x,y,radius float64
}
/* define a rectangle */
type rectangle struct {
width, height float64
}
/* define a method for circle (implementation of shape.area())*/
func(circle circle) area() float64 {
return math.pi * circle.radius * circle.radius
}
/* define a method for rectangle (implementation of shape.area())*/
func(rect rectangle) area() float64 {
return rect.width * rect.height
}
/* define a method for shape */
func getarea(shape shape) float64 {
return shape.area()
}
func main() {
circle := circle{x:0,y:0,radius:5}
rectangle := rectangle {width:10, height:5}
fmt.printf("circle area: %f\n",getarea(circle))
fmt.printf("rectangle area: %f\n",getarea(rectangle))
}
当上述代码编译和执行时,它产生以下结果:
circle area: 78.539816
rectangle area: 50.000000