What's the meaning of interface{}?

后端 未结 6 1251
不思量自难忘°
不思量自难忘° 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:42

    interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface (interface{} is an empty interface).
    In your example, Msg field can have value of any type.

    Example:

    package main
    
    import (
        "fmt"
    )
    
    type Body struct {
        Msg interface{}
    }
    
    func main() {
        b := Body{}
        b.Msg = "5"
        fmt.Printf("%#v %T \n", b.Msg, b.Msg) // Output: "5" string
        b.Msg = 5
    
        fmt.Printf("%#v %T", b.Msg, b.Msg) //Output:  5 int
    }
    

    Go Playground

提交回复
热议问题