Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Interfaces

Go Interfaces

An interface is a type in Go used to define a set of behaviors; by describing the methods a type must implement, it specifies the behavioral contract of the type.

Go provides another data type, namely the interface, which groups together all methods with common characteristics; any other type that implements these methods is considered to implement the interface.

Go's interface design is simple yet powerful, and is an important tool for achieving polymorphism and decoupling.

Interfaces allow us to bind different types to a common set of methods, achieving polymorphic and flexible designs.

Characteristics of interfaces

Implicit implementation:

Interface type variables:

- **Dynamic type**: stores the actual value type. - **Dynamic value**: stores the concrete value.

Zero-value interface:

Empty interface:

Common uses of interfaces

  1. Polymorphism: different types implement the same interface to achieve polymorphic behavior.
  2. Decoupling: define dependencies through interfaces to reduce coupling between modules.
  3. Generalization: use the empty interface interface{} to represent any type.

Interface definition and implementation

An interface is defined using the keyword interface, which contains method declarations.

Example

/* 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*/

}

Define a simple interface:

type Shape interface {

    Area() float64

    Perimeter() float64

}

Implement the interface: A type implements an interface by implementing all the methods required by the interface.

Example

package

main

import

(

       

"fmt"

       

"math"

)

// Define an interface

type

Shape

interface

{

        Area

()

float64

        Perimeter

()

float64

}

// Define a struct

type

Circle

struct

{

        Radius

float64

}

// Circle implements the Shape interface

func

(

c Circle

)

Area

()

float64

{

       

return

math

.

Pi

c

.

Radius

c

.

Radius

}

func

(

c Circle

)

Perimeter

()

float64

{

       

return

2

math

.

Pi

c

.

Radius

}

func

main

()

{

        c

:=

Circle

{

Radius

:

5

}

       

var

s Shape

=

c

// An interface variable can store a type that implements the interface

        fmt

.

Println

(

"Area:"

,

s

.

Area

())

        fmt

.

Println

(

"Perimeter:"

,

s

.

Perimeter

())

}

The output of the code above is:

Area: 78.53981633974483

Perimeter: 31.41592653589793


Empty interface

Empty interface interface{} is a special interface in Go, representing the superset of all types.

Example

package

main

import

"fmt"

func

printValue

(

val

interface

{})

{

        fmt

.

Printf

(

"Value: %v, Type: %T\n"

,

val

,

val

)

}

func

main

()

{

        printValue

(

42

)

       

// int

        printValue

(

"hello"

)

   

// string

        printValue

(

3

.

14

)

     

// float64

        printValue

([]

int

{

1

,

2

})

// slice

}

The output of the code above is:

Value: 42, Type: int

Value: hello, Type: string

Value: 3.14, Type: float64

Value: [1 2], Type: []int


Type assertions

Type assertions are used to extract the underlying value from an interface type.

Basic syntax:



value := iface.(Type)

Example

package

main

import

"fmt"

func

main

()

{

       

var

i

interface

{}

=

"hello"

        str

:=

i

.

(

string

)

// Type assertion

        fmt

.

Println

(

str

)

 

// Output: hello

}

Type assertion with checking

To avoid a panic, you can use a checked type assertion:



value, ok := iface.(Type)

Example

package

main

import

"fmt"

func

main

()

{

       

var

i

interface

{}

=

42

       

if

str

,

ok

:=

i

.

(

string

);

ok

{

                fmt

.

Println

(

"String:"

,

str

)

       

}

else

{

                fmt

.

Println

(

"Not a string"

)

       

}

}

The output of the code above is:

Not a string


Type switch

A type switch is a syntax construct in Go used to execute different logic based on the concrete type of an interface variable.

Example

package

main

import

"fmt"

func

printType

(

val

interface

{})

{

       

switch

v

:=

val

.

(

type

)

{

       

case

int

:

                fmt

.

Println

(

"Integer:"

,

v

)

       

case

string

:

                fmt

.

Println

(

"String:"

,

v

)

       

case

float64

:

                fmt

.

Println

(

"Float:"

,

v

)

       

default

:

                fmt

.

Println

(

"Unknown type"

)

       

}

}

func

main

()

{

        printType

(

42

)

        printType

(

"hello"

)

        printType

(

3

.

14

)

        printType

([]

int

{

1

,

2

,

3

})

}

The output of the code above is:

Integer: 42

String: hello

Float: 3.14

Unknown type


Interface composition

Interfaces can be composed through nesting to achieve more complex behavior descriptions.

Example

package

main

import

"fmt"

type

Reader

interface

{

        Read

()

string

}

type

Writer

interface

{

        Write

(

data

string

)

}

type

ReadWriter

interface

{

        Reader

        Writer

}

type

File

struct

{}

func

(

f File

)

Read

()

string

{

       

return

"Reading data"

}

func

(

f File

)

Write

(

data

string

)

{

        fmt

.

Println

(

"Writing data:"

,

data

)

}

func

main

()

{

       

var

rw ReadWriter

=

File

{}

        fmt

.

Println

(

rw

.

Read

())

        rw

.

Write

(

"Hello, Go!"

)

}


Dynamic value and dynamic type

An interface variable actually contains two parts:

  1. dynamic typing: the concrete type stored in the interface variable.
  2. Dynamic value: the value of the concrete type.

Example of dynamic value and dynamic type:

Example

package

main

import

"fmt"

func

main

()

{

       

var

i

interface

{}

=

42

        fmt

.

Printf

(

"Dynamic type: %T, Dynamic value: %v\n"

,

i

,

i

)

}

The output of the code above is:



Dynamic type: int, Dynamic value: 42


The zero value of an interface

The zero value of an interface is nil.

When both the dynamic type and dynamic value of an interface variable are nil, the interface variable is nil.

Example of interface zero value:

Example

package

main

import

"fmt"

func

main

()

{

       

var

i

interface

{}

        fmt

.

Println

(

i

==

nil

)

// Output: true

}


Practice examples

The following two examples demonstrate the use of interfaces:

Example 1

package

main

import

(

   

"fmt"

)

type

Phone

interface

{

    call

()

}

type

NokiaPhone

struct

{

}

func

(

nokiaPhone NokiaPhone

)

call

()

{

    fmt

.

Println

(

"I am Nokia, I can call you!"

)

}

type

IPhone

struct

{

}

func

(

iPhone IPhone

)

call

()

{

    fmt

.

Println

(

"I am iPhone, I can call you!"

)

}

func

main

()

{

   

var

phone Phone

    phone

=

new

(

NokiaPhone

)

    phone

.

call

()

    phone

=

new

(

IPhone

)

    phone

.

call

()

}

In the example above, we defined an interface Phone, which has a method call(). Then in the main function we define a Phone type variable and assign it the values NokiaPhone and IPhone. Then we call the call() method, and the output is as follows:



I am Nokia, I can call you!

I am iPhone, I can call you!

Second interface example:

Example

package

main

import

"fmt"

type

Shape

interface

{

    area

()

float64

}

type

Rectangle

struct

{

    width  

float64

    height

float64

}

func

(

r Rectangle

)

area

()

float64

{

   

return

r

.

width

r

.

height

}

type

Circle

struct

{

    radius

float64

}

func

(

c Circle

)

area

()

float64

{

   

return

3

.

14

c

.

radius

c

.

radius

}

func

main

()

{

   

var

s Shape

    s

=

Rectangle

{

width

:

10

,

height

:

5

}

    fmt

.

Printf

(

"Rectangle area: %f\n"

,

s

.

area

())

    s

=

Circle

{

radius

:

3

}

    fmt

.

Printf

(

"Circle area: %f\n"

,

s

.

area

())

}

In the example above, we defined a Shape interface, which defines a method area() that returns an area value of type float64. Then we defined two structs, Rectangle and Circle, which implement the Shape interface's area() method respectively. In the main() function, we first define a variable s of type Shape, then assign instances of Rectangle and Circle to it, compute their areas through the area() method and print them. The output is as follows:

矩形面积: 50.000000

圆形面积: 28.260000

It should be noted that an interface type variable can store values of any type that implements the interface. In the example, we assigned instances of both Rectangle and Circle to the variable s of type Shape, and called their area calculation methods through the area() method.