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
+5.5k Golang : Combine slices of complex numbers and operation example
+21.6k Golang : Strings to lowercase and uppercase example
+23.7k Golang : Storing cookies in http.CookieJar example
+12.9k Golang : concatenate(combine) strings
+6k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+5.4k Grep : How to grep for strings inside binary data
+12.7k How to automatically restart your crashed Golang server
+15.5k Golang : How to generate QR codes?
+21.4k Golang : Test file read write permission example
+4.1k Unix/Linux : secure copying between servers with SCP command examples
+5.5k Golang : Embedded or data bundling example
+10.4k How to tell if a binary(executable) file or web application is built with Golang?