Go study notes - interface

Go study notes - interface


An interface is a collection of methods.

An interface is an abstract type that only cares about methods, not data. All that is known is what its methods can do.

Definition of interface:

Each interface consists of several methods, whose definition format is as follows:

type 接口类型名 interface{
    
    
    方法名1( 参数列表1 ) 返回值列表1
    方法名2( 参数列表2 ) 返回值列表2
}
  • Interface Name: Use typethe type name that defines the interface as custom. When naming an interface in Go language, it is generally added after the word er. For example, the interface with write operation is called Writer, the interface with string function is called, Stringeretc. The interface name should preferably highlight the type meaning of the interface.
  • Method name: When the first letter of the method name is uppercase and the first letter of the interface type name is also uppercase, this method can be accessed by code outside the package where the interface is located.
  • Parameter list, return value list: parameter variable names in the parameter list and return value list can be omitted.
//定义接口实现方法
//只要实现这两个方法的类型都可以是geometry类型
type geometry interface {
    
    
	area() float64
	perim() float64
}

Implementation of the interface:

As long as the interface implements all the methods of the object, the interface is implemented.

//定义接口实现方法
//只要实现这两个方法的类型都可以是geometry类型
type geometry interface {
    
    
	area() float64
	perim() float64
}

//自定义结构体类型
type rectangle struct{
    
    
	width,height float64
}

//自定义结构体类型
type circle struct{
    
    
	radius float64
}

//计算矩形面积方法
func (r rectangle) area() float64 {
    
    
	return r.width*r.height
}

//计算矩形周长方法
func (r rectangle) perim() float64 {
    
    
	return 2*r.width+2*r.height
}

//计算圆形面积方法
func (c circle) area() float64 {
    
    
	return math.Pi*c.radius*c.radius
}

//计算圆形周长方法
func (c circle) perim() float64 {
    
    
	return 2*math.Pi*c.radius
}

In the example, it can be seen that we have created two methods for rectangleand , and in the interface , these two methods have been implemented, that is, the interface has been realized.circularea()perim()geometry

Interface type variable:

An interface type variable can store all instances that implement the interface.

//g 就是一个接口类型变量
func measure(g geometry){
    
    
	fmt.Println(g)
	fmt.Println(g.area())
	fmt.Println(g.perim())
}
//接口类型变量作为函数的参数
//实现接口的方法
func main()  {
    
    
	r := rectangle{
    
    3,4}
	c := circle{
    
    5}

	measure(r)
	measure(c)
}

//{3 4}
//12
//14
//{5}
//78.53981633974483
//31.41592653589793

おすすめ

転載: blog.csdn.net/weixin_46435420/article/details/119515908