Usage of interface in Go

后端 未结 4 1770
名媛妹妹
名媛妹妹 2020-11-27 18:26

I would like to understand the interface type with a simple example of it\'s use in Go (Language).

I read the web documentation, but I don\'t get it.

4条回答
  •  旧巷少年郎
    2020-11-27 18:51

    Another working example showing the interaction between an interface and a structure

    package main
    
    import "fmt"
    
    type Info interface {
    Noofchar() int
    Increment()
    }
    
    type Testinfo struct {
    noofchar int     
    }
    
    func (x *Testinfo) Noofchar() int {
    return x.noofchar
    }
    func (x *Testinfo) Increment() {
    x.noofchar++
    }
    
    func main(){
    var t Info = &Testinfo{noofchar:1}
    fmt.Println("No of char ",t.Noofchar())
    t.Increment()
    fmt.Println("No of char ",t.Noofchar())
    }
    

提交回复
热议问题