Page Content

Tutorials

What Is Mean By Object Oriented Programming In GoLang?

Object Oriented Programming In GoLang

Object-Oriented Programming in GoLang is approached differently in Go than in more conventional languages like Java or C++, which mostly rely on inheritance, classes, and objects. For simplicity and conciseness, Go purposefully leaves out features like assertions, method or operator overloading, and type inheritance. Rather, Go emphasises composition over inheritance and incorporates its own techniques to accomplish OOP principles like encapsulation and polymorphism, mostly through structs, functions, and interfaces.

Structs

The core component of Go’s OOP methodology is structures. They enable you to combine several pieces of data (referred to as fields) into a single unit that describes more complex ideas.

To hold a Name (string) and Power (integer), for instance, a Saiyan struct may be defined:

type Saiyan struct {
    Name  string
    Power int
}

Using the new keyword or a composite literal are two methods for creating new struct variables. The freshly allocated object’s pointer is returned by the new keyword.

Methods

The “receiver” in Go refers to a certain type of function that is related with methods. As with methods in standard OOP, you can use this to specify behaviour directly on your custom data types.

The receiver is an additional parameter that comes after the func keyword in the syntax for declaring a method. The Saiyan struct, for example, may have a Super function added:

package main
import "fmt"
type Saiyan struct {
    Name  string
    Power int
}
func (s *Saiyan) Super() {
    s.Power += 10000
}
func main() {
    goku := &Saiyan{Name: "Goku", Power: 9001}
    goku.Super()
    fmt.Println(goku.Power)
}

Output

19001

This example shows that Super works on a pointer to a Saiyan struct since (s *Saiyan) designates s as the receiver of the Super method. Invoking methods usually involves utilising dot notation, which is the preferred style in Go (e.g., goku.Super()). Dereferencing is handled automatically by Go when methods are called on pointer receivers.

Interfaces

A “method set” or a contract of behaviour is defined by an interface, which is an abstract type. To “implement” the interface, they outline a set of methods that a type has to possess. Classes in Go implicitly satisfy their interfaces, in contrast to typical OOP languages where classes explicitly declare that they implement an interface. An interface is said to be satisfied by a type if it implements every method specified by it.

type Shape interface {
    Area() float64
}

For instance, an Area() method could be defined in a Shape interface:

A struct will implicitly satisfy the Shape interface if it defines an Area() function with the given signature, which returns a float64 and accepts no parameters. This enables polymorphism, which means that any concrete type that satisfies an interface can have values in variables of that interface type.

Go’s standard library makes considerable use of simple, frequently one-method interfaces (such as io.Reader, io.Writer, and fmt.Stringer) to encourage flexible, reusable code and provide clear boundaries between components. Io.ReadCloser, which combines io.Reader and io.Closer, is an example of how an interface can be made out of other interfaces.

A value stored in an interface variable can have its underlying concrete type verified using type assertions (x.(T)). This is frequently used when you need to access concrete type-specific methods or fields that are not included in the method set of the interface.

Basically, the foundation of Go’s OOP capabilities is made up of straightforward, explicit features (structs, methods, and implicit interfaces) that, when combined, offer strong tools for efficiently and clearly organising and reusing code without the complications of conventional class hierarchies.

Pointer Receivers vs. Value Receivers

A value-receiving method works on a duplicate of the variable. Any changes made within the method won’t have an impact on the initial variable.

The original variable is accessed via a method implemented with a pointer receiver through its memory address. The method can now alter the original variable as a result. Whether you want the method to alter the original data will determine whether you choose a value or pointer recipient.

Composition and Embedded Types

Go encourages combining objects and reusing code through composition rather than inheritance. You can embed a struct into another struct rather than inheriting properties and behaviours.

For instance, without providing a field name, you can embed the Person struct straight into the Android struct to describe an Android that ‘is a’ Person:

package main
import "fmt"
// Define the Person struct
type Person struct {
    Name string
}
// Define the Talk method for the Person struct
func (p *Person) Talk() {
    fmt.Println("Hi, my name is", p.Name)
}
// Define the Android struct with an embedded Person struct
type Android struct {
    Person // Embedded type
    Model  string
}
// The main function where the program execution begins
func main() {
    // Create an Android instance
    a := new(Android)
    
    // Access the Name field through the embedded Person struct
    a.Person.Name = "R2D2"
    
    // Call the Talk method, which is promoted from the embedded Person type
    a.Talk()
}

Output

Hi, my name is R2D2

Any methods (such as Talk()) provided on the Person struct are automatically accessible through the Android instance when embedding is used:

a := new(Android)
a.Person.Name = "R2D2" // Access embedded field
a.Talk()              // Call embedded method directly on Android

By doing this, languages lacking explicit composition facilities can avoid the laborious process of manually forwarding methods. At first glance, Go’s embedding may seem similar to inheritance, but it is different; the recipient of the forwarded method is still the embedded type rather than the outer type.

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index