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
+12.3k Golang : md5 hash of a string
+9.3k Golang : Write multiple lines or divide string into multiple lines
+22k Golang : Convert string slice to struct and access with reflect example
+8.4k Swift : Convert (cast) Character to Integer?
+26.7k Golang : Encrypt and decrypt data with AES crypto
+9.5k Golang : Find the length of big.Int variable example
+10.6k Generate Random number with math/rand in Go
+6.7k Golang : How to determine if request or crawl is from Google robots
+8.4k Golang : Check if integer is power of four example
+9.7k Golang : Quadratic example
+6.3k Golang : Get missing location after unmarshal binary and gob decode time.
+6.5k Unix/Linux : Use netstat to find out IP addresses served by your website server