Why are interfaces needed in Golang?

后端 未结 6 1760
臣服心动
臣服心动 2020-11-29 19:44

In Golang, we use structs with receiver methods. everything is perfect up to here.
I\'m not sure what interfaces are, however. We define methods in structs and if we wan

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 19:51

    Where I could see interface being useful is with implementing private struct fields. For example if you have this code:

    package main
    type Halloween struct {
       Day, Month string
    }
    func NewHalloween() Halloween {
       return Halloween { Month: "October", Day: "31" }
    }
    func (o Halloween) UK(Year string) string {
       return o.Day + " " + o.Month + " " + Year
    }
    func (o Halloween) US(Year string) string {
       return o.Month + " " + o.Day + " " + Year
    }
    func main() {
       o := NewHalloween()
       s_uk := o.UK("2020")
       s_us := o.US("2020")
       println(s_uk, s_us)
    }
    

    Then o has access to all the struct fields. You may not want that. In that case you can use something like this:

    type Country interface {
       UK(string) string
       US(string) string
    }
    func NewHalloween() Country {
       o := Halloween { Month: "October", Day: "31" }
       return Country(o)
    }
    

    The only change we made was adding the interface, then returning the struct wrapped in the interface. In this case only the methods will have access to the struct fields.

提交回复
热议问题