Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go语言接口
Go语言接口
作者:--    发布时间:2019-11-20

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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册