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
+7.2k Golang : Get Alexa ranking data example
+18.8k Golang : Iterating Elements Over A List
+19k Golang : Read input from console line
+22.4k Golang : Convert seconds to minutes and remainder seconds
+12.4k Golang : Encrypt and decrypt data with x509 crypto
+5.4k Golang : How to deal with configuration data?
+27k Golang : Force your program to run with root permissions
+14.9k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+31.6k Golang : bufio.NewReader.ReadLine to read file line by line
+6.8k Golang : Derive cryptographic key from passwords with Argon2
+18k Golang : Defer function inside init()
+34k Golang : Call a function after some delay(time.Sleep and Tick)