[go] gocron source code reading – empty interface type interface {}

Time:2021-3-3

The action in gocron source code is an empty interface type action interface {}, which can pass any type in. Here, a function is passed in

    command := cli.Command{
        Name:   "web",
        Usage:  "run web server",
        Action: runWeb,
        Flags:  flags,
    }

 

An interface is a contract. As long as any type implements the method in the interface, it can be regarded as realizing the interface. For interface {} types without methods, it can be considered that all types implement this interface, so any type can be passed as a parameter.
The following code declares that a is an empty interface, so any type of data can be saved

    var a interface{}
    a = 1
    fmt.Println(a)
    a = "taoshihan"
    fmt.Println(a)
    a = User{Name: "taoshihan"}
    fmt.Println(a)

 

It is also possible to pass parameters as functions, but when it is used as a return type, it is sometimes necessary to make type assertions and turn the type back to assign values to other variables

func test1(str string) interface{} {
    return str
}
    var b string
    b = test1("taoshihan").(string)
    fmt.Println(b)

Complete source code:

package main

import "fmt"

type User struct {
    Name string
}

//Empty interface as parameter transfer
func test(a interface{}) {
    //You can use this to determine the type
    switch a.(type) {
    case string:
        fmt.Println(a)
    }
}

//Null interface as return
func test1(str string) interface{} {
    return str
}
func main() {
    //Any type can be saved
    var a interface{}
    a = 1
    fmt.Println(a)
    a = "taoshihan"
    fmt.Println(a)
    a = User{Name: "taoshihan"}
    fmt.Println(a)

    //Empty interface as parameter
    test("taoshihan")
    //Here, type assertion is used to return the null interface to string
    var b string
    b = test1("taoshihan").(string)
    fmt.Println(b)
}

 

Recommended Today

Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]