Go (Golang) / Object-Oriented Programming in Go

Defining and Using Structs in Go

In this tutorial, you will learn how to define and use structs in Go. We will cover how to create your own types using structs, and how to define methods on these types.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores how Go implements object-oriented concepts using structs and interfaces.

1. Introduction

In this tutorial, we will explore structs in the Go programming language. Structs allow us to create our own complex types that aggregate together values of other types. They are the building blocks for creating objects and classes in Go.

What you will learn:
- What are structs in Go?
- How to define and create structs.
- How to define methods on structs.

Prerequisites:
- Basic understanding of the Go programming language.
- Familiarity with Go's basic data types (int, float, string, etc.).

2. Step-by-Step Guide

A struct in Go is a user-defined type which allows us to group/combine items of possibly different types into a single type. You can consider a struct a lightweight class that supports encapsulation but lacks inheritance.

Defining a Struct

To define a struct, we use the type keyword, followed by the name of the struct, the struct keyword, and a pair of curly braces {}. Inside the braces, we define the fields of the struct, each on its own line and followed by its type.

For example:

type Person struct {
    Name string
    Age int
}

Here, Person is a struct that contains two fields: Name of type string, and Age of type int.

Creating Struct Instances

To create a new instance of a struct, we use the Person type followed by a pair of curly braces {}. Inside the braces, we initialize each field with a value.

For example:

p := Person{
    Name: "John",
    Age: 30,
}

fmt.Println(p) // prints: {John 30}

Defining Methods on Structs

In Go, you can define methods on user-defined types. A method is a function that has a special receiver argument. The receiver appears in its own argument list between the func keyword and the method name.

For example:

func (p Person) SayHello() {
    fmt.Println("Hello, my name is", p.Name)
}

Here, SayHello is a method on the Person struct. We can call this method on instances of Person:

p := Person{Name: "John", Age: 30}
p.SayHello() // prints: Hello, my name is John

3. Code Examples

Let's go through a few practical examples.

Example 1: Defining and Using a Struct

// Define a new struct type
type Employee struct {
    ID int
    Name string
    Position string
}

// Create an instance of Employee
e := Employee{
    ID: 1,
    Name: "John Doe",
    Position: "Developer",
}

// Access fields in the struct
fmt.Println(e.Name) // prints: John Doe

Example 2: Using Methods on Structs

// Define a new struct type
type Rectangle struct {
    Width float64
    Height float64
}

// Define a method to calculate the area of the rectangle
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

// Create an instance of Rectangle
r := Rectangle{Width: 10, Height: 20}

// Call the Area method
fmt.Println(r.Area()) // prints: 200

4. Summary

In this tutorial, you learned:

  • What structs are in Go and how to define them.
  • How to create instances of your struct types.
  • How to define methods on your struct types.

Next, you could explore more about how to use pointers with structs, anonymous structs, and nested structs.

5. Practice Exercises

  1. Define a Circle struct with a Radius field. Then, define a method Area that calculates the area of the circle (hint: Area = πr^2).

  2. Define a Book struct with Title, Author, and Pages fields. Then, define a method Summary that returns a string summary of the book.

  3. Define a Triangle struct with Base and Height fields. Then, define a method Area that calculates the area of the triangle (hint: Area = 0.5 * Base * Height).

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Converter

Convert between different image formats.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help