What's the meaning of interface{}?

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

    There are already good answers here. Let me add my own too for others who want to understand it intuitively:


    Interface

    Here's an interface with one method:

    type Runner interface {
        Run()
    }
    

    So any type that has a Run() method satisfies the Runner interface:

    type Program struct {
        /* fields */
    }
    
    func (p Program) Run() {
        /* running */
    }
    
    func (p Program) Stop() {
        /* stopping */
    }
    
    • Although the Program type has also a Stop method, it still satisfies the Runner interface because all that is needed is to have all of the methods of an interface to satisfy it.

    • So, it has a Run method and it satisfies the Runner interface.


    Empty Interface

    Here's a named empty interface without any methods:

    type Empty interface {
        /* it has no methods */
    }
    

    So any type satisfies this interface. Because, no method is needed to satisfy this interface. For example:

    // Because, Empty interface has no methods, following types satisfy the Empty interface
    var a Empty
    
    a = 5
    a = 6.5
    a = "hello"
    

    But, does the Program type above satisfy it? Yes:

    a = Program{} // ok
    

    interface{} is equal to the Empty interface above.

    var b interface{}
    
    // true: a == b
    
    b = a
    b = 9
    b = "bye"
    

    As you see, there's nothing mysterious about it but it's very easy to abuse. Stay away from it as much as you can.


    https://play.golang.org/p/A-vwTddWJ7G

提交回复
热议问题