This is an assignment 2 about interface from the course Go: The Complete Developer’s Guide (Golang) by Stephen Grider, this topic is difficult to understand but Stephen explained it well.
Below is the code for the assignment2. So the purpose of interface in golang is to try to reduce the code, while golang is not OOP hence there is no inheritance.
On this assignment2 I need to create a type shape interface
which includes the printArea() float64
which prints out the area of any shapes.
While interface only defines the signature of the function, the implementation under the receiver’s function has to be defined by yourself hence interface cannot check if your implementation is correct or not but it is trying to standardize the argument and the output of the function.
So below is the code for the assignment 2.
package main import "fmt" type square struct { sideLength float64 } type triangle struct { base float64 height float64 } type shape interface { printArea() float64 } func main() { sq := square{6.5} tri := triangle{height: 4.5, base: 3.5} getArea(sq) getArea(tri) } func getArea(sh shape) { fmt.Println(sh.printArea()) } func (sqr square) printArea() float64 { return sqr.sideLength * sqr.sideLength } func (tr triangle) printArea() float64 { return 0.5 * tr.base * tr.height }