OOP in Go: Structs
Table of contents
No headings in the article.
Go is a statically typed language that supports object-oriented programming(OOP) concepts, but is not an OOP programming language.
One of the key features of Go is its support for struct types and interfaces. A struct is similar to a class in object-oriented languages. Go structs allow mimicking OOP features such as Encapsulation, Abstraction and Inheritance.
Encapsulation: Go structs can be used to encapsulate data and methods together.
Inheritance: A struct can contain fields of other structs, which can be used to achieve composition and code reuse.
Polymorphism: Go doesn't have traditional polymorphism like inheritance-based languages, but it provides interface-based polymorphism.*
Abstraction: By grouping related data and methods in a struct, the rest of the program can interact with it through a simple interface without knowing the underlying implementation details.
In this blog post, we will discuss Go structs and their usage in the language.
Structs are user-defined types that group together zero or more values under a single name. In Go, a struct is defined using the type
keyword followed by the name of the struct and the keyword struct
.
type Person struct {
name string
age int
netIncome int
debt int
}
type Employee struct {
Person
salary int
}
In the above example, we created Person
and Employee
structs. Note that the Employee
struct implements the Person
struct but also has an additional field, salary. We can create a new Person
object by initializing its fields with values.
p := Person{name: "John", age: 30, netIncome: 50000, debt: 10000}
Here, we created a Person
p and populated the fields with values. We can now have p as an Employee
with a salary of ₹60,000.
e := Employee{Person: p, salary: 60000}
Structs can also have methods associated with them, which can be defined as regular functions, with additional receiver arguments.
func (p Person) NetWorth() int {
return p.netIncome - p.debt
}
In the above example, we defined a method NetWorth() that calculates the net worth of p. By defining the method with p as receiver argument, we can access the fields of p.
In this blog post, we explored the basics of defining and using Go structs by creating a Person and Employee struct with fields and methods, and initializing their values. We also briefly touched on receiver arguments, which are used in defining methods associated with structs.
* Interfaces and Receivers will be covered in detail in future blog posts.