What's the meaning of interface{}?

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

    It's called the empty interface and is implemented by all types, which means you can put anything in the Msg field.

    Example :

    body := Body{3}
    fmt.Printf("%#v\n", body) // -> main.Body{Msg:3}
    
    body = Body{"anything"}
    fmt.Printf("%#v\n", body) // -> main.Body{Msg:"anything"}
    
    body = Body{body}
    fmt.Printf("%#v\n", body) // -> main.Body{Msg:main.Body{Msg:"anything"}}
    

    This is the logical extension of the fact that a type implements an interface as soon as it has all methods of the interface.

提交回复
热议问题