Golang : Implementing class(object-oriented programming style)
If you are used to ways of doing things in Java or C++, such as declaring class and assigning different methods to the class. Golang has a unique way of implementing class with the type interface. This code example below demonstrate how to declare classes and assign methods to the classes.
package main
import (
"fmt"
)
type SayHelloIntFace interface {
SayHello()
}
type Person struct{}
// this method is tied to Person class
func (person Person) SayHello() {
fmt.Printf("Hello!")
}
type Dog struct{}
// this method is tied to Dog class
func (dog Dog) SayHello() {
fmt.Printf("woof! woof!")
}
func greeting(i SayHelloIntFace) {
i.SayHello()
}
func main() {
// instantiate objects
person := Person{}
dog := Dog{}
var i SayHelloIntFace
fmt.Println("\nPerson : ")
i = person
greeting(i)
fmt.Println("\n\nDog : ")
i = dog
greeting(i)
}
Output :
Person :
Hello!
Dog :
woof! woof!
Hope you may find this tutorial useful. Good luck in learning and using Golang for developing your website or application!
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+20.7k Golang : Underscore or snake_case to camel case example
+7.3k Golang : Process json data with Jason package
+6.2k Golang : Test input string for unicode example
+8.7k Golang : Heap sort example
+5.2k Golang : Reclaim memory occupied by make() example
+8.9k Golang : Handle sub domain with Gin
+13.7k Golang : Convert spaces to tabs and back to spaces example
+5.5k Unix/Linux : How to find out the hard disk size?
+8.1k Golang : Qt splash screen with delay example
+7.4k Golang : Handling Yes No Quit query input
+10.9k Golang : Fix go.exe is not compatible with the version of Windows you're running
+12.2k Golang : 2 dimensional array example