A Programmer's Guide To Go Part 2 - Objects and Interfaces |
Written by Mike James | ||||
Thursday, 25 July 2019 | ||||
Page 3 of 3
InterfacesThere is still a small problem that we have to solve but it isn't obvious at first. As Go is statically typed you can't make a mistake using non-existent methods. For example, if you try:
then you will generate a compile time error. The compiler can check to see if point has an area method and when it finds it doesn't it flags the error. Now consider the problem of writing a function that can work with any "shape" object that has an area method - e.g. circle and ellipse from the previous section. What you want to write is something like:
This doesn't work because function parameters have to be typed. One solution is to assign a specific type:
To avoid having to define a function for each type Go has interface types. An interface type is a collection of methods or a "method set". For example we could define a measurable interface as the method set that consists of just one member - i.e. the area function.
Of course an interface type can have lots of methods defined not just one. If you know about interfaces as implemented in other languages you might be expect that each of object that supports the interface would have to declare this fact. That is, to be regarded as an example of an interface type an object could have to declare that it implements the interface. This is not how Go works. In Go the set of methods that an object supports can be worked out by the compiler, so why bother the programmer with the need to declare that an object implements an interface - it either does or it doesn't. So, for example, after you have declared the measurable interface you can write a function that makes use of it as its parameter type - eg.
Now you can call display with any object that has the draw method in its method set. That is both:
work without any modifications to circle or ellipse. That is, an object satisfies an interface if it contains the method set of the interface within its method set. Notice also that as almost any type can have methods the range of possible things that can satisfy an interface is wider than you might expect. And that's all there is to the interface type and how you use it.
More Information:Related articles:Go Programming Language Turns 3 Getting started with Google's Go Why invent a new language? Go creator explains Ready to Go - Go Reaches Version 1 Google App Engine Go-es Forward Go with Google - Yet Another Language! A Programmers Guide To LanguagesContents
<ASIN:0321817141> <ASIN:1478355824> |
||||
Last Updated ( Saturday, 03 August 2019 ) |