SoFunction
Updated on 2025-03-04

This article will help you understand the use of interfaces in Go

interface

existGoIn a language, an interface is an abstract type, a collection of methods. The purpose of an interface is to define the specification, and the details of the specification are implemented by other objects. Let's take a look at an example:

import "fmt"

type Person struct {
    Name string
}

func main() {
    person := Person{Name: "cmy"}
    (person) // {cmy}
}

The above code defines the structurePersonmainThe function creates a variable for this structureperson, and then passfmtIn the bagPrintlnThe function prints this structure and the print result is{cmy}. On this basis, let's modify the code:

import "fmt"

type Person struct {
    Name string
}

func (p Person) String() string {
    return ("name: %s", )
}

func main() {
    person := Person{Name: "cmy"}
    (person) // name: cmy
}

The newly modified code is a structurePersonAdd a structure methodString() string, the return result of the method is correctnameFor formatting, we print the structure again, and the observation results show thatString()The value returned by the method, not{cmy}. Why is this so? This is because(T)In the implementation details of the function, the structure will be judged. If the structure is implemented,StringerThe interface will be printed directlyString()The return value of the method. Here is the code for the Stringer interface:

type Stringer interface {
    String() string
}

The structure implements this interface, which means complying with the specifications defined by this interface.(T)Functions find that the structure has this specification, so the information will be printed according to the specification. based onStringerFor interface, let’s take a look at the syntax format of the interface:

type XXX interface {
    // methods
}

1、type

The declaration of the interface must betypeStart with keywords.

2. Interface name

The camel-style nomenclature is recommended. The method names with capital letters can be accessed outside the package, while those with lowercase letters can only be accessed inside the package.

3、interface

The interface identification.

4. Interface body

Declare specifications in braces, that is, declare methods, and methods must have names.

Implementation of interfaces

existGoIn languages, the implementation of an interface is not based on an interface, but on a method. If a custom type has all the methods of an interface, then this custom type implements this interface. The implementation of the interface is reflected in the above examples.PersonThe structure is definedString() stringMethod, ownedStringerAll methods of the interface are implementedStringerinterface.

A custom type can implement multiple interfaces

type A interface {
        a()
}

type B interface {
        b()
}
type Person struct {
        Name string
}

func (p Person) a() {
}

func (p Person) b() {
}

AThe interface is declaredamethod,BThe interface is declaredbmethod,PersonThe structure is definedaandbTwo methods, soPersonThe structure has been implementedAandBTwo interfaces.

Interface type variable

Once the interface is defined, it can be used to declare variables.

import "fmt"

type A interface {
}

func main() {
    var a A
    (a) // <nil>
}

If only interface variables are declared and not initialized, the value of the variable is defaultnil, because the interface type is actually a pointer. If you assign an initial value to an interface, you need to select a legal value, that is, the assigned base class must implement this interface.

Empty interface

existGoIn the language, it can be considered that all types implement empty interfaces, because empty interfaces do not have any methods.

import "fmt"

type EmptyInterface interface {
}

func main() {
    var a EmptyInterface = 1
    var b EmptyInterface = true
    var c EmptyInterface = "hello"
    var d EmptyInterface = 3.14
    var e EmptyInterface = 'c'
    (a, b, c, d, e) // 1 true hello 3.14 99
}

All types implement empty interfaces, so empty interface variables can be assigned initial values ​​as values ​​or variables of any type.

Type Assertion

GoThe language supports type assertion operation. Through this operation, the rvalue (the initial value assigned) of the interface variable can be restored. The syntax form of type assertions is usually:

v, ok := a.(T)

If the assertion is successful, thenvThe value of the interface variable is the value of the interface variable.okThe value oftrue;If the assertion fails,vThe value ofTzero value of type,okThe value offalse

Type assertion variant type switch

passtype switch, you can determine which dynamic type the interface variable belongs to.

import "fmt"

type EmptyInterface interface {
}

func main() {
    var a EmptyInterface = 1
    switch a.(type) {
    case string:
	("The rvalue of a is string")
    case int:
	("The rvalue of a is int")
    case bool:
	("The rvalue type of a is bool")
    case float64:
	("The rvalue type of a is float64")
    }
}

summary

This article first introduces the definition of the interface, and then uses an example to understand one of the application scenarios of the interface, the syntax format and implementation methods of the introduction interface, then introduces the characteristics and type assertions of the empty interface, and finally introduces the type assertions of the variant.type switchExamples of application.

This is the article about this article about how to use interfaces in Go. For more relevant Go language interface content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!