[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

Taro3. 4 example of developing wechat applet

1、 Install scaffolding and initialize project Install scaffold Scaffolding Initialization is shown in the figure below. Select vue3, less and vue3 nutui templates: initialization 2、 Installation package audit and version check After installation, some alarm prompts may appear and prompt NPM audit, as shown in the following figure Installation package audit If you ignore it, […]