English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang basic tutorial

Golang control statements

Golang function & method

Golang struct

Golang slice & array

Golang string (String)

Golang pointer

Golang interface

Golang concurrency

Golang exception (Error)

Other Golang items

Go Language Interface (Interfaces)

Go language interfaces are different from other languages. In Go language, an interface is a custom type used to specify a set of one or more method signatures, and the interface is abstract, so you are not allowed to create an instance of the interface. However, you can create a variable of the interface type, and you can assign a specific type value that has the methods required by the interface to the variable. In other words, an interface is both a set of methods and a custom type.

How to create an interface?

In Go language, you can use the following syntax to create an interface:

type interface_name interface{
    //Method signature
}

For example:

//Create an interface
type myinterface interface{
    // Methods
    fun1() int
    fun2() float64
}

Here, the interface name is included between the type and interface keywords, and the method signature is included within the curly braces.

How to implement an interface?

In Go language, in order to implement an interface, all the methods declared in the interface must be implemented. Go language interfaces are implicitly implemented. Like other languages, it does not contain any specific keyword for implementing the interface. As shown in the following example:

// Golang program explains how
//Implement the interface
package main
import "fmt"
//Create an interface
type tank interface {
    // Methods
    Tarea() float64
    Volume() float64
}
type myvalue struct {
    radius float64
    height float64
}
//Implementation method
//Tank interface
func (m myvalue) Tarea() float64 {
    return 2*m.radius*m.height + 2*3.14*m.radius*m.radius
}
func (m myvalue) Volume() float64 {
    return 3.14 * m.radius * m.radius * m.height
}
func main() {
    // Access using the bucket's interface
    var t tank
    t = myvalue{10, 14}
    fmt.Println("The area of the bucket:", t.Tarea())
    fmt.Println("The capacity of the bucket:", t.Volume())
}

Output:

The area of the bucket: 908
The capacity of the bucket: 4396

Precautions

  • The zero value of the interface is nil.

  • When the interface contains zero methods, this type of interface is called an empty interface. Therefore, all types implement an empty interface.

    Syntax:

    interface{}
  • Interface type:The interface has two types, one is static and the other is dynamic. The static type is the interface itself, for example, tank in the following example. However, the interface does not have a static value, so it always points to a dynamic value.
    The variable of interface type, which contains the value of the type that implements the interface, so the value of this type is called a dynamic value, and the type is a dynamic type. It is also called a concrete value and a concrete type.

    //Explain the concept of Go program
    //Dynamic values and types
    package main
    import "fmt"
    //Creating an interface
    type tank interface {
        // Methods
        Tarea() float64
        Volume() float64
    }
    func main() {
        var t tank
        fmt.Println("The interface value of tank is: ", t)
        fmt.Printf("The type of tank is: %T ", t)
    }

    Output:

    The interface value of tank is: <nil>
    The type of tank is: <nil>

    In the above example, there is an interface named tank. In this example,fmt.Println("The interface value of tank is: ", t) The statement returns the dynamic value of the interface, while the statement fmt.Printf("The type of tank is: %T ", t) returns the dynamic type of the interface, which is nil, because the interface here does not know who is implementing it.

  • Type assertion:In Go language, type assertion is an operation applied to interface values. In other words, type assertion is the process of extracting interface values.

    Syntax:

    a.(T)

    Here, a is the value or expression of the interface, and T is the type assertion type also known as type assertion. Type assertion is used to check if the dynamic type of its operand matches the asserted type. If T is a concrete type, the type assertion checks if the given dynamic type of a equals T, and here, if the check is successful, the type assertion returns the dynamic value of a. Otherwise, if the check fails, a panic exception will occur. If T is an interface type, the type assertion checks if the given dynamic type satisfies T, and here, if the check is successful, the dynamic value is not extracted.

    //Type assertion 
    package main 
      
    import "fmt"
      
    func myfun(a interface{}) { 
      
        //Extract the value of a
        val := a.(string) 
        fmt.Println("value: ", val) 
    } 
    func main() { 
      
        var val interface { 
        } = "w3codebox"
          
        myfun(val) 
    }

    Output:

    value:3codebox

    In the above example, if the value ofval := a。(string)statement changed toval := a。(int)then the program will throw a panic exception. Therefore, to avoid this problem, we use the following syntax:

    value, ok := a.(T)

    Here, if the type of a equals T, the value contains the dynamic value of a, and ok is set to true. And if the type of a does not equal T, ok is set to false and the value contains the zero value, and the program will not throw a panic exception. As shown in the following program:

    package main
    import "fmt"
    func myfun(a interface{}) {
        value, ok := a.(float64)
        fmt.Println(value, ok)
    }
    func main() {
        var a1 interface {
        } = 98.09
        myfun(a1)
        var a2 interface {
        } = "w3codebox"
        myfun(a2)
    }

    Output:

    98.09 true
    0 false
  • Type assertion:In Go interfaces, type assertion is used to compare the specific type of an interface with multiple types provided in the case statements. It is similar to type declaration, but with a distinction that uppercase specifies the type, not the value. You can also compare types with interface types. As shown in the following example:

    package main
    import "fmt"
    func myfun(a interface{}) {
        //Use type assertion
        switch a.(type) {
        case int:
            fmt.Println("Type: int, value: ", a.(int))
        case string:
            fmt.Println("\nType: string, value: ", a.(string))
        case float64:
            fmt.Println("\nType: float64, value: ", a.(float64))
        default:
            fmt.Println("\nType not found")
        }
    }

    Output:

    Type: string, value:3codebox
    Type: float64, value:  67.9
    Type not found
  • Interface usage:When you want to pass different types of parameters in a method or function, you can use an interface, just like the Println() function. Or, you can also use an interface when multiple types implement the same interface.