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
+17k Golang : Find IP address from string
+10.8k Golang : Print UTF-8 fonts on image example
+5.2k Golang : Experimental emojis or emoticons icons programming language
+15.6k Golang : Get input from keyboard
+16.5k Golang : Simple client server example
+16.9k Golang : Get download file size
+11.3k Golang : Arithmetic operation with numerical slices or arrays example
+7.2k Your page has meta tags in the body instead of the head
+5.6k Golang : Spell checking with ispell example
+21.5k Golang : Get ASCII code from a key press(cross-platform) example
+6.8k Golang : get the current working directory of a running program