Golang working with interfaces and functions -3
When learning Golang one of the interesting part is interfaces. It has a little bit difference with respect to other languages. Let me start with how to identify a typical interface and structs and go over.
Here it is following sample interface;
By identifying this interface we expect to implement any structs with respect to its aim. Let me more specific. GetArea method should have math definition that calculates area of received shape.
On the following the calculation square and triangle ;
As it is mentioned previous reading they are receiver functions. So same function receives (not parameter) different shapes to calculate area.
Golang Receiver Functions -2 (buraktunali.blogspot.com)
We can safely use getArea methods for these structs. In order to call getArea method we should create a function that gets interface as a parameter which also call the method according to type of struct.
Square or Triangle structs can be passed to printArea method and getArea can be callable with the help of Area interface.
As you see methods can get interfaces so that make necessary calls.
https://pkg.go.dev/ here is the Golang package documentation site. There many interfaces implemented by other packages which can be passed safely.
To illustrate,
https://pkg.go.dev/net/http#Get
Http package has FileSystem interface and its open method returns File interface refering to io package interface and its operation. What does it mean ?
It means other functions can be callable in io packages which gets "File" interface. As "File" interface has io.Reader interface it can be passed to functions.
Have a good work.
Yorumlar
Yorum Gönder