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
+24.5k Golang : Change file read or write permission example
+5.8k Golang : Error handling methods
+24.6k Golang : GORM read from database example
+20.7k Golang : Read directory content with os.Open
+10.3k Golang : Random Rune generator
+6.2k Linux/Unix : Commands that you need to be careful about
+7.3k Golang : File system scanning
+14k Golang : How to determine if a year is leap year?
+8.3k Swift : Convert (cast) Character to Integer?
+8.2k Golang : Get final or effective URL with Request.URL example
+14.1k Golang : Compress and decompress file with compress/flate example
+15.9k Golang : Get digits from integer before and after given position example