This is a creation in Article, where the information may have evolved or changed.
The keyword interface in Go is given a lot of different meanings. Each type has an interface, which means that a collection of methods is defined for that type.
This code defines the struct type S with a field and two methods. Type S struct {i int}func (P *s) Get () int {return p.i}func (P *s) Put (v int) {p.i = v}//Define interface Type I interface {Ge The t () int Put (int)}//is a legitimate implementation for interface I,s because it defines the two methods required for I. Note: This is true even if you do not explicitly define S to implement I. The properties of the Go program interface value: Func f (P I) {//define a function to accept an interface type as the parameter fmt. Println (P.get ())//P implements interface I, must have a get () method P.put (1)//Put () method is similar//the variable p here holds the value of the interface type. }//called var s Sf (&s)//Because s implements the I, can invoke F to pass a pointer to its value of type S//Get the address of S, rather than the value of s, because the method is defined on the pointer of S, see Code 5.1 above. This is not necessary-you can define the method to accept the value-but then the put method does not work as expected. Define another type to implement the same interface I:type R struct {i int}func (P *r) Get () int {return P.I} func (P *r) Put (v int) {P.i=v}//function f can now be connected A variable of type R or S. Suppose you need to know the actual type in function f. You can use type switch to get it in go. Func f (P I) {switch t:p. (type) {//type), used in the switch statement (type). Save the type into the variable T. It is illegal to use (type) outside of switch. Case *s:case *r:case s:case r:defaut: The}}//type judgment is not the only way to get the type at run time. To get the type at run time, you can also use "comma, OK" to determine whether an interface type implements a particular interface: if T, OK: = P. (*s); OK {fmt. Printf ("%d\n", T.get ())}Determine that a variable implements an interface that can be used: t: = P. (*s)
Null interface
interface{} // 每个类型都能匹配到空接口func g(something interface{}) int { // 用空接口作为参数的函数 return something.(I).Get() // 值 something 具有 类型 interface{},这意味着方法没有任何约束:它能包含任何类型。.(I) 是 类型 断言,用于转换 something 到 I 类型的接口。// 如果有这个类型,则可以调用 Get() 函 数。因此,如果创建一个 *S 类型的新变量,也可以调用 g(),因为 *S 同样实现了空 接口。}s = new(S)fmt.Println(g(s)) // 打印0// 如果调用g()的参数没有实现I,会在运行时得到警告,如i:=5 fmt.Println(g(i)) // 在运行时警告:panic: interface conversion: int is not main.I: missing method Get,这是没有问题的,因为内建类型int没有Get()方法。
Method
The method is to have the function of the recipient, you can define the method on any type (except for the non-local type, including the built-in type: int type cannot have a method). However, you can create a new integer type that has a method.
type Foo intfunc (f Foo) Emit(){ fmt.Printf("%v",f)}type Emitter interface{ Emit()}func (i int) Emit() {....}
An interface is defined as a collection of methods. Method contains the actual code. In other words, an interface is defined, and the method is implemented. Therefore, the recipient is undefined as an interface type, which causes the invalid receiver type compilation error
The recipient type must be T or *t, where T is the type name. T is called the recipient base type or short base type. The underlying type must not make a pointer or interface type, and is defined in the same package as the method.
It is meaningless to create pointers to interfaces in go. It is also illegal to actually create a pointer to an interface value.
Interface Name
According to the rules, the single-method interface is named method name plus-er suffix: reader,writer,formatter, etc.
There are a bunch of such names that efficiently reflect their responsibilities and the names of the functions they contain. Read,write,close, flush,string, etc. have a normative statement and meaning. To avoid confusion, do not let the same name be used unless there is a similar declaration and meaning. Conversely, if a type implements the same method as a well-known type, the same name and declaration are used, and the string conversion method is named string instead of ToString.
Bubble Sort Integer Data
func bubblesort(n []int) { for i:=0; i< len(n)-1; i++ { for j:=i+1; j< len(n); j++ { if n[j]<n[i] { n[i], n[j] = n[j], n[i] } } }}
A similar sort string
Func bubblesortstring (n []string) {/ .... / }
Based on this, it may take two functions, one per type. This can be made more generic by using interfaces.
The following method cannot be used
func sort(i []interface{}) { // 函数将接受一个空接口的slice switch i.(type) {// 使用type switch找到输入参数实际的类型 case string: // 排序 // .... case int: // ... } return /*....*/ //返回排序后的slice}
However, if you call this function with sort ([]int{1,4,5}), it will fail: cannot use I (Type []int) as type []interface in function argment
This is because go cannot (implicitly) convert to slice.
So the "general" function of Go form needs to be created by means of an interface.
Steps:
1. Define an interface function with a number of sorting-related methods (this is called sorter). At least need to get slice length function, compare two values of function and exchange function;
type Sorter interface { Len() int // len()作为方法 Less(i,j int) bool // p[j]<p[i]作为方法 Swap(i,j int) // p[i],p[i] = p[j],p[i]作为方法}
2. Define a new type for sorting slice. Note that the slice type is defined;
type Xi []inttype Xs []string
3. How to implement the Sorter interface.
//整数为:func (p Xi) Len() int { return len(p) }func (p Xi) Less(i int, j int) bool { return p[j]<p[i] }func (p Xi) Swap(i int, j int) { p[i],p[j]=p[j],p[i] }// 字符串的:func (p Xs) Len() int { return len(p) } func (p Xs) Less(i int, j int) bool { return p[j] < p[i] } func (p Xs) Swap(i int, j int) { p[i], p[j] = p[j], p[i]
4. Write a general sort function that acts on the sorter interface.
func Sort(x Sorter) {// x现在是Sorter类型; for i:=0; i<x.Len()-1; i++ { for j:=i+1; j<x.Len(); j++ { if x.Less(i, j) { x.Swap(i, j) } } }}// 现在可以像下面这样使用通用的 Sort 函数:ints := Xi{44, 67, 3, 17, 89, 10, 73, 9, 14, 8}strings := Xs{"nut", "ape", "elephant", "zoo", "go"}Sort(ints)fmt.Printf("%v\n", ints)Sort(strings)fmt.Printf("%v\n", strings)