Go language interface definitions and usage examples

  • 2020-06-01 09:57:53
  • OfStack

This article illustrates the definition and usage of interfaces in the Go language. I will share it with you for your reference as follows:

In Go, the interface interface actually means the same thing as interfaces in other languages. interface understands it as one type of specification or convention. Does type 1 "implement" an interface? It depends on whether this type implements all the methods defined in the interface.

1. Definition and use of interface.

Such as

type I interface{
    Get() int

This defines an interface that contains two functions, Get and Put

Ok, one of my interfaces implements this interface:

type S struct {val int}
func (this *S) Get int {
    return this.val
func (this *S)Put(v int) {
    this.val = v

This structure, S, implements the interface I

2. Empty interface

For empty interfaces interface{} is actually very similar to the concept of generics. Any type implements an empty interface.

Here's an example:

1 function implements such a function:

Take any object as a parameter, and if the object implements interface I, call the Get method of interface I

Many languages have this logic:

function g(obj){
    if (obj is I) {
        return (I)obj.Get()

Go is implemented like this:
func g(any interface{}) int {
    return any.(I).Get()

Is this any.(I) very semantic? "Any object that implements the I interface"

3. interface in Go:

Here are some examples of interface:

func SomeFunction(w interface{Write(string)}){

In this case, interface is directly defined in the parameter, which is special...
func weirdFunc( i int ) interface{} {
  if i ==  0 {
    return "zero"
  return i;

In this example, since it is possible to return string or int, the return value is set to interface, which is commonly seen in Go's package package.

I hope this article has been helpful to you in the programming of Go language.

Related articles: