DEV Community

Cover image for How to Write Classes in Golang
Santosh Kumar
Santosh Kumar

Posted on • Originally published at santoshk.dev

How to Write Classes in Golang

Introduction

I have seen many people coming from Python background struggling with Go. What I have obeserved it they write code that is limited to writing functions and calling them. They never leverage design constructs such as abstraction, encapsulation, inheritance, composition etc. I can understand their pain because I've been in the same boat.

In today's post I'll compare how we write classes in Python vs how we do the same thing in a Go way.

What is a class composed of?

  1. Attributes in form of variables
  2. Behavior in form of methods

Example in Python

Consider the following code in Python that defines a simple Person class with a name attribute and a greet method:

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, my name is {self.name}")

p = Person("John")
p.greet()  # prints "Hello, my name is John"
Enter fullscreen mode Exit fullscreen mode

If you're a Python programmer looking to learn Go, you'll be happy to know that Go has a similar concept to classes called "structs". Structs are similar to classes in that they allow you to define a custom data type with its own fields and methods.

Struct to define the structure and attributes

To define a struct in Go, you use the type keyword followed by the name of the struct and a set of curly braces containing the fields. Here's an example of a simple struct called Person:

type Person struct {
    name string
    age  int
}
Enter fullscreen mode Exit fullscreen mode

This defines a struct called Person with two fields: name and age, both of which are of type string and int respectively.

Method or behaviour using receiver function

You can also define methods on your structs by using the func keyword and attaching the method to the struct using the (p *Person) syntax, where p is the receiver of the method and Person is the type of the receiver. Here's an example of a method called SayHello that prints a greeting to the console:

func (p *Person) SayHello() {
    fmt.Printf("Hello, my name is %s and I am %d years old\n", p.name, p.age)
}
Enter fullscreen mode Exit fullscreen mode

To create an instance of a struct, you can use the new function or the shorthand syntax :=. Here's an example of both:

// Using the new function
p1 := new(Person)
p1.name = "John"
p1.age = 30

// Using the shorthand syntax
p2 := Person{name: "Jane", age: 25}
Enter fullscreen mode Exit fullscreen mode

You can also define a "constructor" function to create instances of your struct. This can be useful if you want to perform some initialization logic when creating a new instance. Here's an example of a constructor function for the Person struct:

func NewPerson(name string, age int) *Person {
    p := new(Person)
    p.name = name
    p.age = age
    return p
}
Enter fullscreen mode Exit fullscreen mode

You can then use this constructor function to create a new instance of the Person struct like this:

p := NewPerson("Bob", 35)
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial has helped you understand how to define and use structs in Go as a Python programmer. Structs are a powerful and flexible way to define custom data types in Go, and I encourage you to explore them further.

Thank you for reading!

Top comments (4)

Collapse
 
milhamh95 profile image
Muhammad Ilham hidayat • Edited

just set the struct field value directly

type Person struct {
    name string
    age  int
}

func (p *Person) SayHello() {
    fmt.Printf("Hello, my name is %s and I am %d years old\n", p.name, p.age)
}

p := Person{name: "Jane", age: 25}
Enter fullscreen mode Exit fullscreen mode

No need to create NewPerson function. Go don't have class

Collapse
 
santosh profile image
Santosh Kumar

Yes, we definately don't need NewPerson. It's merely a layer of abstraction. We can hinder how the object is instanciated if we want in NewPerson.

Collapse
 
delta456 profile image
Swastik Baranwal

In Go, we do not have classes but we have structs.

Collapse
 
santosh profile image
Santosh Kumar

Yes, that's true. This post is for people coming from languages who have encountered classes before but don't know about structs.