Home  >  Article  >  Backend Development  >  What is an interface in golang

What is an interface in golang

藏色散人
藏色散人Original
2019-12-25 17:19:473291browse

What is an interface in golang

golang What is an interface?

If goroutine and channel are the two cornerstones of Go concurrency, then interfaces are the key to data types in Go language programming. In the actual programming of Go language, almost all data structures revolve around interfaces, and interfaces are the core of all data structures in Go language.

Related recommendations: golang tutorial

Interface in golang

1. Interface

Concept: The interface defines a set of methods, but does not contain the specific implementation of these methods; they are abstract, and the interface cannot contain variables.

Definition format of interface

type Namer interface {
method1() return_type
method2() return_type
}

2. An example of an interface

    package main
    import "fmt"
    
    type Message interface {
        Send()
    }
    type user struct {
        name string
        score int
    }
    func (u *user) Send() {
        fmt.Println("hi", u.name, "this is your ", u.score)
    }
    func sendMessage(msg Message) {
        msg.Send()
    }
    func main() {
        u := &user{name: "roty", score: 44}
        sendMessage(&u)
    }

Interface in Golang makes coding more flexible and easy to expand , making Go possess the characteristics of object-oriented polymorphism.

It is enough for us to remember three points here:

● Collection of method declarations

● Any type of object implements everything declared in the interface method, indicating that the type implements the corresponding interface.

● Can be used as a data type, and any object that implements this interface can assign values ​​to the corresponding interface type variables.

Combine examples to understand the above three points:

package main
import "fmt"
import "math"
// 几何图形的接口(interface)
type geometry interface {
    area() float64
    perim() float64
}
// rect 和 circle 实现 geometry 接口
type rect struct {
    width, height float64
}
type circle struct {
    radius float64
}
// 实现了接口中声明的所有方法即实现了该接口,这里 rects 实现了 geometry 接口
func (r rect) area() float64 {
    return r.width * r.height
}
func (r rect) perim() float64 {
    return 2*r.width + 2*r.height
}
// circles 实现 geometry 接口
func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
    return 2 * math.Pi * c.radius
}
// 定义的接口可以作为一种数据类型,当一个变量的类型为一个接口类型时,这个变量可以调用接口中定义的方法。
// 这里定义一个函数,接收一个类型为 geometry 的参数变量
func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}
func main() {
    r := rect{width: 3, height: 4}
    c := circle{radius: 5}
    // The circle and rect struct types both implement the geometry interface so we can use instances of these structs as arguments to measure.
    // rect 和 circle 结构类型都实现了 geometry 接口,所以我们能够把它们的对象作为参数传给 measure 函数
    // 在 measure 函数内部,参数对象调用了所属类型实现的接口方法。
    measure(r)
    measure(c)
}

As long as a type implements the method declared by the interface, it is considered to have implemented the interface. The same type can support the implementation of multiple interfaces at the same time. An interface Can also be implemented by multiple types. If a type implements an interface, then objects of this type can be assigned to variables of this interface type.

package main
import "fmt"
type I interface {
  method1()
}
type T struct{}
func (T) method1()  {}
func main()  {
  var i I = T{}
  fmt.Println(i)
}

The last part explains the interface{} type. This type of interface does not declare any method, commonly known as empty interface. Because any type of object implements the empty interface by default (as mentioned above, as long as any type implements the interface method, it will implement the corresponding interface. Since the empty interface has no methods, all types implement the empty interface by default). When you need any Very useful in the context of type variables.

package main
import (
    "fmt"
)
func PrintAll(vals []interface{}) {
    for _, val := range vals {
        fmt.Println(val)
    }
}
func main() {
    names := []string{"stanley", "david", "oscar"}
    vals := make([]interface{}, len(names))
    for i, v := range names {
        vals[i] = v
    }
    PrintAll(vals)
}
// stanley
// david
// oscar

The above is the detailed content of What is an interface in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What can golang develop?Next article:What can golang develop?