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
+47.3k Golang : Upload file from web browser to server
+11.6k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+9.7k Golang : Underscore string example
+8.6k Golang : Accessing content anonymously with Tor
+20.1k Golang : Sort and reverse sort a slice of strings
+5.4k Javascript : Generate random key with specific length
+9.3k Golang : Read file and convert content to string
+18.3k Golang : Fix cannot download, $GOPATH not set error
+7.7k Android Studio : Import third-party library or package into Gradle Scripts
+26k Golang : Find files by name - cross platform example
+7.3k Golang : How To Use Panic and Recover