How to Implement Object-Oriented Programming Concepts in Go

Object-oriented programming (OOP) is a programming paradigm that relies on objects as a central concept. In OOP, code is formatted based on function, allowing code maintainability, abstraction, reusability, efficiency, and multiple functions on the object.

An object has properties (variables) that define the characteristics, properties and methods (functions) that define the actions (procedures) and behavior of the object.

Object-oriented programming in Go is different from other languages. Object-oriented concepts are implemented in Go using structs, interfaces, and custom types.


Customize types in Go

Custom types make it easy to group and define similar code for reuse.

The code to declare custom types is:

type typeName dataType 

When creating a custom type and specifying a variable, you can check the type using reflect.TypeOf() takes a variable and returns the type of the variable.

import( "fmt"
"reflect")
type two int
var number two
fmt.Println(reflect.TypeOf(number))

MAKE A VIDEO OF THE DAY

The numbers variable is a type two is an integer. You can go further to create more custom types.

Creating structs in Go

Structs are the blueprints for object-oriented programming in Go. A structure is a collection of user-defined fields.

A structure can contain many different data types, including complex types and methods.

You can create a structure using the following syntax:

type StructName struct {
}

Normally, structure names are usually capitalized and camelcased for readability.

The struct type takes the field name and data type. Structs can take any Go data type, including custom types.

type User struct {
field1 string
field2 int
fieldMap map[string]int
}

You can initialize a struct type by assigning the struct as a variable.

instance := User{
}

The struct instance can be populated with fields on the initialization as defined at initialization or set to null.

instance := User{
field1: "a string field",
field2: 10,
fieldMap: map[string]int{},
}

Accessing structure elements

You can access the fields of a struct instance using the dot notation for the field.

fmt.Println("Accessing a field of value", instance.field2)

This outputs field2 of the initialized struct instance.

Assign methods to structs

Functions (methods) are assigned to struct types by specifying the receiver name and struct name before the function name as shown in the syntax below.

func (receiver StructName) functionName() {
}

Method Function name can only be used on the specified struct type.


Implement Inheritance in Go

Inheritance is the ability of objects and types to access and use the methods and properties of other objects. Go does not have Inheritance, but you can use compositions. In Go, the component requests a reference to a superstructure (inherited structure) in a substructure by providing the superstructure’s name to the substructure.

Using the structure example above:

type User struct {
field1 string
field2 int
fieldMap map[string]int
}
type User2 struct {
User
}

By the way pass it User structure name to User2 struct, the User2 struct can access all methods and properties of User structs on initialization except that abstraction techniques are used.

son := User2{
User{
field1: "baby",
field2: 0,
fieldMap: nil,
},
}
fmt.Println(son.field2)


The Boy the variable above is the initialization of User2 structure. As seen in the example, Boy variables can access and initialize values ​​of type User and use them.

Encapsulating Type Fields in Go

Encapsulation, also known as “information hiding”, is a technique for wrapping an object’s methods and properties into units to restrict use and access except as specified (allowing special features). read/write permissions).

Encapsulation is done in Go using exported and unexported identifiers in packages.

Exported Identifiers (Read and Write)

Exported identifiers are exported from their defined packages and access to other programs. Capitalizing the field identifier will output the fo field.

type User struct {
Field1 string
Field2 int
FieldMap map[string]int
}
type User2 struct {
User
}


Unreported Identifiers (Read Only)

Unreported identifiers are not exported from the specified package and are conventionally lowercase.

type User struct {
field1 string
field2 int
fieldMap map[string]int
}
type User2 struct {
User
}

The concept of exported and unexported identifiers also applies to an object’s methods.

Polymorphism in Go

Polymorphism is a technique used to give different forms to an object for flexibility.

Go implements polymorphism using interfaces. Interfaces are custom types used to define method signatures.

Declare the interface

An interface declaration is similar to a structure declaration. However, interfaces are declared using display key word.

type InterfaceName interface{
}

The interface declaration contains the methods implemented by the struct types.

Implement interfaces in structs

The types that implement the interface must be declared then the methods of the type that implement the interface.


type Color interface{
Paint() string
}
type Green struct {
}
type Blue struct {
}

The above code has a Color interface declared with Paint method implemented by Green and Blue structure types.

Interfaces are implemented by assigning methods to struct types and then naming the method according to the method the interface is implemented.

func (g Green) Paint() string {
return "painted green"
}
func (b Blue) Paint() string {
return "painted blue"
}

Paint method implemented by types Green and Blue, can now be called and used Paint method.

brush := Green{}
fmt.Println(brush.Paint())

The “painted green” printed on the console verifies that the interface has been successfully implemented.

Abstract fields in Go

Abstraction is the process of hiding unimportant methods and properties of a type, making it easy to secure parts of a program from unusual, unintended use.

Go has no immediately implemented abstraction; however, you can work our way through implementing abstraction using interfaces.


type Human interface {
run() string
}
type Boy struct {
Legs string
}
func (h Boy) run() string {
return h.Legs
}

The above code generates a Mankind interface with a run interface returns a string. The Boy implementation type run method of Mankind interface and returns a string on initialization.

One of the ways to implement abstraction is to make a struct inherit the interface whose methods will be abstracted. There are other approaches, but this is the easiest.

type Person struct {
Name string
Age int
Status Human
}
func main() {
person1 := &Boy{Legs: "two legs"}
person2 := &Person{
Name: "amina",
Age: 19,
Status: person1,
}
fmt.Println(person.Status.run())
}

The Person inherited struct Mankind interface and can access all its methods using variable Status interface inheritance.

When initialized by reference (using pointers), the version of Person structure Person2 refer to an instance of Boy structure Person1 and have access to the methods.

This way you can specify specific methods to be implemented in the style.

OOP vs functional programming

Object-oriented programming is an important paradigm because it gives you more control over your program and encourages code reuse in ways that functional programming doesn’t.

This doesn’t make functional programming a bad choice, as functional programming can be useful and better for some use cases.


internal object-oriented programming

What is object-oriented programming? The basics are explained in layman’s terms

Continue reading


About the author

https://www.makeuseof.com/how-to-implement-object-oriented-programming-concepts-in-go/ How to Implement Object-Oriented Programming Concepts in Go

Sarah Ridley

USTimesPost.com is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@ustimespost.com. The content will be deleted within 24 hours.

Related Articles

Back to top button