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
+13.7k Golang : Accurate and reliable decimal calculations
+3.9k Nginx and PageSpeed build from source CentOS example
+6.6k Golang : Command line ticker to show work in progress
+6.1k Golang : How to detect if a sentence ends with a punctuation?
+8.5k Golang : Qt get screen resolution and display on center example
+6.7k Gogland : Where to put source code files in package directory for rookie
+9k Golang : Use regular expression to get all upper case or lower case characters example
+10.3k Golang : Display a text file line by line with line number example
+26k PHP : Count number of JSON items/objects
+20.5k Golang : Convert seconds to minutes and remainder seconds
+5.8k Golang : Get expvar(export variables) to work with multiplexer
+9.7k Golang : Create Temporary File