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
+22k Golang : Convert seconds to minutes and remainder seconds
+4.4k Java : Generate multiplication table example
+20.4k Golang : Pipe output from one os.Exec(shell command) to another command
+22.1k Golang : Repeat a character by multiple of x factor
+17.2k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+5.9k Golang : Shuffle array of list
+12.2k Golang : List running EC2 instances and descriptions
+18.5k Golang : Generate thumbnails from images
+4.7k Which content-type(MIME type) to use for JSON data
+6.6k Golang : Skip or discard items of non-interest when iterating example
+18.8k Golang : Padding data for encryption and un-padding data for decryption
+8k Golang : How To Use Panic and Recover