Usage of interface in Go

后端 未结 4 1765
名媛妹妹
名媛妹妹 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:47

    In this example, I'm using the interface to demonstrate how to achieve polymorphism in Golang.

    package main 
    
    
    import(
        "fmt"
        "math"
    )
    
    func main(){
        rect := Rectangle{20,50}
        cir := Circle{2}
    
        //According to object you passed in getArea method, 
        // it will change the behaviour and that is called Polymorphism.
        fmt.Println("Area of Rectangle =",getArea(rect))
        fmt.Println("Area of Circle =",getArea(cir))
    
    }
    
    //Interface Shape with one area method
    type Shape interface{
         area() float64
    }
    
    //Creating Rectangle and Circle type using struct 
    type Rectangle struct{
        height float64
        width float64
    }
    
    type Circle struct{
        radius float64
    }
    
    //Receiver function, which implements struct's area methods
    func(r Rectangle) area() float64{
        return r.height * r.width
    }
    
    func(c Circle) area() float64{
        return math.Pi * math.Pow(c.radius,2)
    }
    
    //passing interface as arguments, which can calculate shape of any mentioned type
    //All the struct are tied together because of the Interface.
    func getArea(shape Shape) float64{
        return shape.area()
    }
    

提交回复
热议问题