interface in the go language USES instances

  • 2020-05-30 20:23:37
  • OfStack

In the go language, interface is a collection of 1 set of unimplemented methods that implement the interface if an object implements all the methods in the interface. Unlike other object-oriented languages, go does not need to show which interface the declaration calls.

package main
import (
type I interface {
 Get() int
type S struct{ i int }
func (p *S) Get() int  { return p.i }
func (p *S) Put(v int) { p.i = v }
type R struct{ i int }
func (p *R) Get() int  { return p.i }
func (p *R) Put(v int) { p.i = v }
func f1(p I) {
//interface{} Empty interface, can accept any type. .(I) Is a type assertion used for conversion something to I Type interface
func f2(p interface{}) {
 if t, ok := p.(S); ok {
  fmt.Println("S:", t)
 } else if t, ok := p.(I); ok {
  fmt.Println("I:", t.Get())
func f3(p interface{}) {
 switch t := p.(type) {
 case S:
  fmt.Println("S:", t.Get())
 case R:
  fmt.Println("R:", t.Get())
 case I:
  fmt.Println("I:", t.Get())
  fmt.Println("unknow type")
func main() {
 s := S{101}
 r := R{1111}

The above structure S implements both methods of I, so S implements I. Because S implements I, you can call f to pass an S type merit pointer to it.

The summary is as follows:
(1) use "comma, ok" to determine whether an interface type implements a specific interface:

if t, ok := something.(I) ; ok {
// For some interfaces are implemented I the
// t Is the type it owns

(2) a variable of type interface can store any variable of type that implements all the methods in interface
(3) empty interface can represent any type and can be used as parameter and return type

package main
import "fmt"
func main() {
 var i interface{} = 100
 var s interface{} = "hello"
 fmt.Printf("i = %d, s = %s\n", i, s)
 s = i
 fmt.Printf("i = %d, s = %d\n", i, s)

(4) interface combination

Embedding one interface1 into the declaration of another interface2 is equivalent to including the functions of interface1 into interface2, but different combinations have duplicate methods

a. As long as the list of methods in two interfaces is the same (regardless of order), it is the same interface and can be assigned to each other
The list of methods for b.interface1 is a subset of the list of methods for another interface2. interface2 can be assigned to interface1; otherwise, the method in interface2 will override the method with the same name in interface1
c. interface can be embedded in a package

Related articles: