What's the meaning of interface{}?

后端 未结 6 1360
不思量自难忘°
不思量自难忘° 2020-11-22 10:55

I\'m new to interfaces and trying to do SOAP request by github

I don\'t understand the meaning of

Msg interface{}

in this code:

6条回答
  •  甜味超标
    2020-11-22 11:57

    An example that extends the excellent answer by @VonC and the comment by @NickCraig-Wood. interface{} can point to anything and you need a cast/type assertion to use it.

    package main
    
    import (
        . "fmt"
        "strconv"
    )
    
    var c = cat("Fish")
    var d = dog("Bone")
    
    func main() {
        var i interface{} = c
        switch i.(type) {
        case cat:
            c.Eat() // Fish
        }
    
        i = d
        switch i.(type) {
        case dog:
            d.Eat() // Bone
        }
    
        i = "4.3"
        Printf("%T %v\n", i, i) // string 4.3
        s, _ := i.(string)      // type assertion
        f, _ := strconv.ParseFloat(s, 64)
        n := int(f)             // type conversion
        Printf("%T %v\n", n, n) // int 4
    }
    
    type cat string
    type dog string
    func (c cat) Eat() { Println(c) }
    func (d dog) Eat() { Println(d) }
    

    i is a variable of an empty interface with a value cat("Fish"). It is legal to create a method value from a value of interface type. See https://golang.org/ref/spec#Interface_types.

    A type switch confirms i interface type is cat("Fish") . See https://golang.org/doc/effective_go.html#type_switch. i is then reassigned to dog("Bone"). A type switch confirms that i interface’s type has changed to dog("Bone") .

    You can also ask the compiler to check that the type T implements the interface I by attempting an assignment: var _ I = T{}. See https://golang.org/doc/faq#guarantee_satisfies_interface and https://stackoverflow.com/a/60663003/12817546.

    All types implement the empty interface interface{}. See https://talks.golang.org/2012/goforc.slide#44 and https://golang.org/ref/spec#Interface_types . In this example, i is reassigned, this time to a string "4.3".i is then assigned to a new string variable s with i.(string) before s is converted to a float64 type f using strconv. Finally f is converted to n an int type equal to 4. See What is the difference between type conversion and type assertion?

    Go's built-in maps and slices, plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly. See https://golang.org/doc/faq#generics.

提交回复
热议问题