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

pros, cons, and How to Use Flutter
Softwares

pros, cons, and How to Use Flutter

by admin
June 13, 2025
AI trends shaping software development in 2025
Softwares

AI trends shaping software development in 2025

by admin
June 15, 2025
Apple debuts Liquid Glass interface at design-focused WWDC event
Softwares

Apple debuts Liquid Glass interface at design-focused WWDC event

by admin
June 10, 2025
Learn How to Build a WordPress Block Theme Style Variation — Speckyboy
Softwares

Learn How to Build a WordPress Block Theme Style Variation — Speckyboy

by admin
June 11, 2025
User Guide for Odoo Website SSLCommerz Payment Acquirer
Softwares

User Guide for Odoo Website SSLCommerz Payment Acquirer

by admin
June 9, 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
Android Developer vs. Web Developer: Key Differences

Android Developer vs. Web Developer: Key Differences

September 12, 2022
The Comprehensive Multivitamin for Everyday Glow

The Comprehensive Multivitamin for Everyday Glow

April 24, 2022
Getting Started with Git and GitHub

Getting Started with Git and GitHub

December 26, 2021
The Best Crime Shows on Netflix

The Best Crime Shows on Netflix

May 27, 2023
Deal Alert! Save 50% On Yankee Candles – Hollywood Life

Deal Alert! Save 50% On Yankee Candles – Hollywood Life

November 26, 2022
4 cryptocurrency companies in S’pore that are still standing strong

4 cryptocurrency companies in S’pore that are still standing strong

May 13, 2021
Volty 2.5 – 30V DC voltmeter review – It’s a Leatherman voltmeter in my pocket and I’m happy to see you!

Volty 2.5 – 30V DC voltmeter review – It’s a Leatherman voltmeter in my pocket and I’m happy to see you!

April 3, 2022
Toolbar customization and disabling the autoplay of videos – Vivaldi Browser snapshot 2679.3

Toolbar customization and disabling the autoplay of videos – Vivaldi Browser snapshot 2679.3

May 24, 2022
Calendar of New Movie Releases

Calendar of New Movie Releases

June 15, 2025
OMG! Is David Beckham FINALLY Extending An Olive Branch To Son Brooklyn Amid Family Feud?

OMG! Is David Beckham FINALLY Extending An Olive Branch To Son Brooklyn Amid Family Feud?

June 15, 2025
The Boys Star Erin Moriarty Reveals Graves’ Disease Diagnosis

The Boys Star Erin Moriarty Reveals Graves’ Disease Diagnosis

June 15, 2025
iPhone 17 Pro: Apple A19 Pro Chip Could Match M4’s Performance

iPhone 17 Pro: Apple A19 Pro Chip Could Match M4’s Performance

June 15, 2025
It’s Game (Almost) Over In the Final Squid Game Trailer

It’s Game (Almost) Over In the Final Squid Game Trailer

June 14, 2025
‘Bridgerton’ Actress Genevieve Chenneour Fought With Phone Thief

‘Bridgerton’ Actress Genevieve Chenneour Fought With Phone Thief

June 14, 2025
Oscar-winner Gary Oldman reveals story behind his famously panned movie Tiptoes

Oscar-winner Gary Oldman reveals story behind his famously panned movie Tiptoes

June 14, 2025
In a Shocking Twist of Fate, ‘Cobra Kai’ Proved That Mr. Miyagi’s True Successor Was Never Daniel, but This Character

In a Shocking Twist of Fate, ‘Cobra Kai’ Proved That Mr. Miyagi’s True Successor Was Never Daniel, but This Character

June 14, 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

  • Calendar of New Movie Releases
  • OMG! Is David Beckham FINALLY Extending An Olive Branch To Son Brooklyn Amid Family Feud?
  • The Boys Star Erin Moriarty Reveals Graves’ Disease Diagnosis
  • 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.

New Self New Life