Go with OOP

Sakib Sami
LiveKlass
Published in
2 min readOct 11, 2017

Go / Golang is a modern programming language developed by Google. Though Go is not an Object Oriented Programming language like Java, C#, Python, or other programming languages, there is a way to achieve this.
Then, Let's see how one can achieve OO behavior in a Go program.

Class vs Structure

There is struct instead of class in go. And you can achieve the behavior of a class in go using struct. Let's see an example,

public class Student() {
private String name;
private String dept;
public Student() {}public Student(String name, String dept){
this.name = name;
this.dept = dept;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getDept(){
return this.dept;
}
public void setDept(String dept){
this.dept = dept;
}
}

Equivalent code in go,

type Student struct {
name string
dept string
}
func NewStudent(name string, dept string) Student {
return Student{
name: name,
dept: dept,
}
}
func (s *Student) GetName() string {
return s.name
}
func (s *Student) SetName(name string) {
s.name = name
}
func (s *Student) GetDept() string {
return s.dept
}
func (s *Student) SetDept(dept string) {
s.dept = dept
}

Note : In go properties starts with anything other than uppercase is not accessible from outside of package.

Inheritance vs Composition

type TA struct {
Student
_Courses []string
}
func NewTA(name string, dept string, courses []string) TA {
return TA{
Student{
name: name,
dept: dept,
},
courses,
}
}
func (ta *TA) SetCourses(courses []string) {
ta._Courses = courses
}
func (ta *TA) GetCourses() []string {
return ta._Courses
}

Composition is a way of embedding one structure within another. In above example embedded Student structure in TA. And by this you can achieve behaviour of the embedded structure too.

Encapsulation

In go fields, methods, structures name starts with anything other than uppercase are private by default from outside of package.
consider the above example.

Polymorphism

import "fmt"type DriverInfo interface {
GetInfo() string
}
type Driver struct {
Name string
}
type CarDriver struct {
Driver
}
type MotorDriver struct {
Driver
}
func (d Driver) GetInfo() string {
return d.Name + ", Driver"
}
func (cd CarDriver) GetInfo() string {
return cd.Name + ", CarDriver"
}
func (md MotorDriver) GetInfo() string {
return md.Name + ", MotorDriver"
}
func main() {
d := Driver{Name: "A"}
cd := CarDriver{Driver{Name: "B"}}
md := MotorDriver{Driver{Name: "C"}}
fmt.Println(d.GetInfo())
fmt.Println(cd.GetInfo())
fmt.Println(md.GetInfo())
}

Example of method overriding. Go doesn’t support method overloading.

Abstraction

One can achieve abstraction using interface.
Consider the above example.

Originally published at www.sakib.ninja on October 11, 2017.

--

--

Sakib Sami
LiveKlass

Senior Software Engineer @ Twilio | Entrepreneur | Tech Ninja