New Self New Life
No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
New Self New Life
No Result
View All Result
Home Softwares

Introduction to Object-oriented Programming in Go

by admin
3 years ago
in Softwares
Understanding Control Structures in Go
Share on FacebookShare on Twitter


Not like many well-liked languages like Java and C++, Go isn’t an object oriented language per se. Within the Go programming language, builders have to drive create object-oriented type with the minimal language help that it gives. Perceive that the paradigm of object-oriented expertise is extra conceptually imbibed throughout the construct of the language that helps it. That being mentioned, most general-purpose languages that will not be object-oriented can mimic object-oriented rules. A programming language could inherently have little or no or restricted help in implementing the rules of object-oriented programming. Nevertheless, a pure object-oriented language is extra pleasant to object-oriented rules and has an express help of its options, resembling inheritance, polymorphism, encapsulation, and so forth. Right here, on this programming tutorial, we are going to introduce a number of the primary OOP options of Go and the Golang programming language.

Learn: Understanding Rubbish Assortment in Go

Is Go an OOP Language?

Go isn’t an OOP language – that a lot is for positive. However, can we use go language options to satisfy the rules of the object-oriented methodologies? Sure, builders can, to some extent. For instance, Go has no help of inheritance, however the thought will be compensated for with its help of composition. Equally, a type of polymorphism can be created utilizing interfaces. Perceive that, if one really desires to develop an utility based on the object-oriented methodologies, Go is unquestionably not a good selection. Moderately, one ought to search for languages like Java, C++, Python or every other excessive functioning language that helps object-oriented options.

If you’re interested by utilizing Interfaces in Go to imitate polymorphism and OOP ideas, you possibly can try our tutorial: Introduction to Interfaces in Go.

Easy methods to Create Objects in Go and Golang

The important thing thought behind object-orientation is to separate the code into a number of manageable elements or objects. Every object has its personal id that’s decided by the information (attributes) and the strategies (conduct) that function on the info. The attributes are sometimes hidden and may solely be accessed via the strategies outlined throughout the object. That is referred to as encapsulation. Not like Java or C++, each of which use courses to create the container or summary information sort, Go can encapsulate its attributes utilizing struct.

Object-oriented programming in Golang

Within the above picture, the thing description could look one thing like this Go instance code:

package deal payroll

sort Worker struct {
	Id    int
	title  string
	cellphone string
	electronic mail string
}

The above Golang code defines the summary information sort with attributes. As soon as it has been created we are able to instantiate it as follows:

e1 := payroll.Worker{Id: 101}

or:

e1 := payroll.Worker{}

or:

var ep1 *payroll.Worker
ep1 = &payroll.Worker{Id: 102}
ep1.SetEmployee("Anita", "4787753", "[email protected]")

Information Hiding in Go

However, what if we write the code as follows:

e1 := payroll.Worker{Id: 101, title:"Anita",cellphone:"2783648",electronic mail:"[email protected]" } // Error!

This isn’t going to work. The reason being accessibility. Not like Java or C++, the place we have now personal or public to limit the accessibility of attributes, Go has no such options. As a substitute, what it gives is a way for package-level accessibility. Observe that we have now written Id within the Worker construction, with the primary letter in uppercase. Which means the attribute Id will be accessed instantly outdoors the package deal when the thing is created, whereas the attributes resembling title, cellphone, and electronic mail are written in lowercase and may solely be accessed via member strategies, which, in Go, are outlined as follows:

func (e *Worker) GetName() string {
	return e.title
}
func (e *Worker) SetName(title string) {
	e.title = title
}

The above code gives a way to implement a type of encapsulation in Go. To rapidly take a look at the thought, right here is the whole code:

package deal payroll

sort Worker struct {
	Id    int
	title  string
	cellphone string
	electronic mail string
}

func (e *Worker) SetEmployee(title, cellphone, electronic mail string) {
	e.SetName(title)
	e.SetPhone(cellphone)
	e.SetEmail(electronic mail)
}

func (e *Worker) GetId() int {
	return e.Id
}
func (e *Worker) GetName() string {
	return e.title
}
func (e *Worker) GetPhone() string {
	return e.cellphone
}
func (e *Worker) GetEmail() string {
	return e.electronic mail
}
func (e *Worker) SetId(id int) {
	e.Id = id
}
func (e *Worker) SetName(title string) {
	e.title = title
}
func (e *Worker) SetPhone(cellphone string) {
	e.cellphone = cellphone
}
func (e *Worker) SetEmail(electronic mail string) {
	e.electronic mail = electronic mail
}

//-------------------------------------------------------------
package deal principal

import (
	"fmt"
	"oop_prog/payroll"
)

func principal() {
	e1 := payroll.Worker{Id: 101}
	e1.SetEmployee("Bob", "82347783", "[email protected]")
	fmt.Println(e1.GetId(), ":", e1.GetName(), ":", e1.GetPhone(), ":", e1.GetEmail())
}

Wish to study extra about struct? We’ve got a programming tutorial that may train you extra: Understanding Structs in Go.

Inheritance by Composition in Go

As inheritance isn’t supported instantly in Go, what programmers can do is use composition to get a number of the impact of it. Composition mainly means placing a number of objects into one other object like an attribute. Due to this fact, we are able to create a struct sort that embeds different struct varieties. For instance, a pc is a composition of parts like CPU, RAM, HDD, a Motherboard and different stuff.

Right here is a few instance code demonstrating inheritance by composition in Go:

package deal laptop

import "fmt"

sort CPU struct {
	structure string
}

func (cpu *CPU) SetArchitecture(arch string) {
	cpu.structure = arch
}

func (cpu *CPU) GetArchitecture() string {
	return cpu.structure
}

sort RAM struct {
	dimension int
}

func (ram *RAM) SetSize(dimension int) {
	ram.dimension = dimension
}

func (ram *RAM) GetSize() int {
	return ram.dimension
}

sort Motherboard struct {
	class string
}

func (m *Motherboard) SetCategory(cat string) {
	m.class = cat
}

func (m *Motherboard) GetCategory() string {
	return m.class
}

sort Pc struct {
	cpu    CPU
	ram    RAM
	mboard Motherboard
}

func (c *Pc) SetSpecification(cpu CPU, ram RAM, mboard Motherboard) {
	c.cpu.SetArchitecture(cpu.GetArchitecture())
	c.ram.SetSize(ram.GetSize())
	c.mboard.SetCategory(mboard.GetCategory())
}

func (c *Pc) ShowSpecification() {
	fmt.Println("CPU: ", c.cpu.GetArchitecture(), ", RAM: ", c.ram.GetSize(), "GB, Motherboard: ", c.mboard.GetCategory())
}

//-------------------------------------

package deal principal

import (
	"fmt"
	"oop_prog/laptop"
)

func principal() {
	cpu := laptop.CPU{}
	cpu.SetArchitecture("64-bit")

	ram := laptop.RAM{}
	ram.SetSize(8)

	mboard := laptop.Motherboard{}
	mboard.SetCategory("Micro ATX")

	c1 := laptop.Pc{}
	c1.SetSpecification(cpu, ram, mboard)
	c1.ShowSpecification()
}

The issue with regular inheritance is that it results in a hierarchy of courses. The conduct of the ultimate object is usually buried or unfold throughout the hierarchy. Furthermore, any change within the superclass, or in any class within the hierarchy, can have a ripple impact. A bug crept into the branches of inheritance may be very troublesome to debug. The composition utilized in Go is definitely a advantageous option to delegate conduct of the thing. In keeping with object-oriented methodology, composition creates a has-a relationship amongst objects, whereas in regular inheritance the connection among the many object known as an is-a relationship.

The fantastic thing about composition is that many easy object constructs will be mixed to create a extra complicated object solely when wanted. It signifies that builders can lazy-create objects solely when wanted. This retains reminiscence allocation to a minimal, resulting in a lesser reminiscence footprint of this system.

In our instance above, we have now created objects like CPU, RAM and Motherboard and outlined their attributes and strategies. As we create a Pc, we are able to mix the person objects right into a extra complicated object.

Learn: Understanding Rubbish Assortment in Go

Polymorphism in Go

Polymorphism is one other key function of object oriented programming. It gives the flexibility to put in writing code via the implementation of varieties that may tackle totally different conduct at runtime. In Go, polymorphism is achieved via interfaces and interfaces solely. As soon as an interface implements a kind, the performance outlined inside it’s open to any values of that sort. The usual library is replete with this implementation. For instance, the io package deal has an intensive set of interfaces and features to stream information effectively in our code. Here’s a fast instance as an instance how polymorphic conduct is achieved via interfaces in Go:

package deal polymorph

import (
	"fmt"
	"math"
)

sort Form interface {
	space()
}

sort Rectangle struct {
	X1, Y1, X2, Y2 float64
}

sort Circle struct {
	Xc, Yc, Radius float64
}

func (r *Rectangle) space() {
	fmt.Println("Rectangle Space : ", (r.X2-r.X1)*(r.Y2-r.Y1))
}

func (c *Circle) space() {
	fmt.Println("Circle Space: ", math.Pi*math.Pow(c.Radius, 2))
}

func GetArea(s Form) {
	s.space()
}

//--------------------------------------------------

package deal principal

import "oop_prog/polymorph"
func principal() {
	r := polymorph.Rectangle{10, 10, 20, 20}
	polymorph.GetArea(&r)
	c := polymorph.Circle{5, 5, 30}
	polymorph.GetArea(&c)

}

Within the code above the 2 struct varieties Rectangle and Circle implement the Form interface. Consequently, the struct turns into sort Form and it may be handed to the perform GetArea. On this method, we are able to add as many struct varieties as we wish or want; so long as it implements the Form interface, the dynamic conduct of the GetArea technique shall be determined at runtime.

As an apart, you possibly can study extra in regards to the io package deal on this Golang programming tutorial: Easy methods to Carry out Fundamental I/O Operations in Go.

Last Ideas on OOP and Go

Many of the object-oriented methodologies are literally conceptual. Due to this fact, if the design is believed out rigorously, doing object-oriented programming in any language is definitely doable. Pure object-oriented languages simply present further help. Though implementing each object-oriented function isn’t doable in Go, a number of the key options can simply be applied. Overlook about object-oriented, these options can be utilized in any method the programmer likes. That’s truly the crux of the matter.

Learn extra Go and Golang programming tutorials.



Source link

Tags: IntroductionObjectorientedProgramming
Previous Post

The Ballad of Songbirds and Snakes Logo Revealed in Teaser Trailer

Next Post

4 ways to improve your productivity at work with a smartwatch – Noise

Related Posts

Verification framework uncovers safety lapses in open-source self-driving system
Softwares

Verification framework uncovers safety lapses in open-source self-driving system

by admin
May 23, 2025
Customizable Tab Bar – Vivaldi Browser snapshot 3704.3
Softwares

Customizable Tab Bar – Vivaldi Browser snapshot 3704.3

by admin
May 25, 2025
PrestaShop Free Gift Products | Add Free Products to Cart
Softwares

PrestaShop Free Gift Products | Add Free Products to Cart

by admin
May 22, 2025
30+ Best Lightroom Presets for Stunning Portraits in 2025 — Speckyboy
Softwares

30+ Best Lightroom Presets for Stunning Portraits in 2025 — Speckyboy

by admin
May 24, 2025
The emperors of AI coding tools have no clothes – and it’s creating a productivity delusion
Softwares

The emperors of AI coding tools have no clothes – and it’s creating a productivity delusion

by admin
May 20, 2025
Next Post
4 ways to improve your productivity at work with a smartwatch – Noise

4 ways to improve your productivity at work with a smartwatch – Noise

Just what’s happening with the metaverse?

Just what's happening with the metaverse?

  • Trending
  • Comments
  • Latest
barnacle boi Releases Thumping ‘Introspect’ EP

barnacle boi Releases Thumping ‘Introspect’ EP

November 15, 2023
Australian Music Festival Forced to Cancel Due to 529% Government-Imposed Price Hike: Report

Australian Music Festival Forced to Cancel Due to 529% Government-Imposed Price Hike: Report

May 9, 2024
10 of the Best Must-Read Classic Books

10 of the Best Must-Read Classic Books

September 25, 2022
Most Useful Gadgets in 2021 – Nogentech.org

Most Useful Gadgets in 2021 – Nogentech.org

July 29, 2021
15 Best Movies Like Parasite

15 Best Movies Like Parasite

February 20, 2022
Getting Started with Apache Maven (JAVA/J2EE)

Getting Started with Apache Maven (JAVA/J2EE)

April 23, 2021
PrestaShop PayPal Recurring Payment Gateway {User Guide}

PrestaShop PayPal Recurring Payment Gateway {User Guide}

January 29, 2022
The Comprehensive Multivitamin for Everyday Glow

The Comprehensive Multivitamin for Everyday Glow

April 24, 2022
Vince Gill Admits Eagles’ Sphere Visuals Are ‘Pretty Distracting’

Vince Gill Admits Eagles’ Sphere Visuals Are ‘Pretty Distracting’

May 25, 2025
Google Discover Gets Quiet Redesign, Emphasizing News Sources

Google Discover Gets Quiet Redesign, Emphasizing News Sources

May 25, 2025
”Even if I’m fired,I stay,” declares Cannes chief Thierry Frémaux

”Even if I’m fired,I stay,” declares Cannes chief Thierry Frémaux

May 25, 2025
Hailey Bieber Supports Justin Bieber’s Rare Live Performance

Hailey Bieber Supports Justin Bieber’s Rare Live Performance

May 25, 2025
Justin Bieber Performs Steamy Duet With SZA Onstage — While Hailey Was In The Audience! See Her Reaction!

Justin Bieber Performs Steamy Duet With SZA Onstage — While Hailey Was In The Audience! See Her Reaction!

May 25, 2025
Ryan Reynolds Thinks ‘Star Wars’ Is Ready to Be R-Rated

Ryan Reynolds Thinks ‘Star Wars’ Is Ready to Be R-Rated

May 24, 2025
Actors Who Allegedly Tried To Get Costars Fired

Actors Who Allegedly Tried To Get Costars Fired

May 24, 2025
Which Celebrities Attended Diddy’s White Parties? – Hollywood Life

Which Celebrities Attended Diddy’s White Parties? – Hollywood Life

May 24, 2025
New Self New Life

Your source for entertainment news, celebrities, celebrity news, and Music, Cinema, Digital Lifestyle and Social Media and More !

Categories

  • Celebrity
  • Cinema
  • Devices
  • Digital Lifestyle
  • Entertainment
  • Music
  • Social Media
  • Softwares
  • Uncategorized

Recent Posts

  • Vince Gill Admits Eagles’ Sphere Visuals Are ‘Pretty Distracting’
  • Google Discover Gets Quiet Redesign, Emphasizing News Sources
  • ”Even if I’m fired,I stay,” declares Cannes chief Thierry Frémaux
  • Home
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites. slotsfree  creator solana token

No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites.

real slots real money online