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 Your page has meta tags in the body instead of the head
+12.4k Golang : Get dimension(width and height) of image file
+13.6k Golang : Execute function at intervals or after some delay
+24.1k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+16.2k Golang : How to make a file read only and set it to writable again?
+16.2k Golang : When to use init() function?
+23k Golang : Daemonizing a simple web server process example
+8.5k Facebook : Getting the friends list with PHP return JSON format
+21.7k Golang : Strings to lowercase and uppercase example
+16.7k Golang : Get all upper case or lower case characters from string example
+9.4k Golang : Allow Cross-Origin Resource Sharing request
+5.9k Golang : constant 20013 overflows byte error message