DEV Community

Cover image for Deep Dive into Go Struct
Leapcell
Leapcell

Posted on

Deep Dive into Go Struct

In Go, struct is an aggregate type used for defining and encapsulating data. It allows combining fields of different types. Structs can be seen as custom data types similar to classes in other languages, but they do not support inheritance. Methods are functions associated with a specific type (often a struct) and can be called using an instance of that type.

Defining and Initializing Structs

Defining a Struct

Structs are defined using the type and struct keywords. Here's an example of a simple struct definition:

type User struct {
  Username    string
  Email       string
  SignInCount int
  IsActive    bool
}
Enter fullscreen mode Exit fullscreen mode

Initializing a Struct

Structs can be initialized in various ways.

Initializing with Field Names

user1 := User{
  Username:    "alice",
  Email:       "alice@example.com",
  SignInCount: 1,
  IsActive:    true,
}
Enter fullscreen mode Exit fullscreen mode

Initializing with Default Values

If some fields are not specified, they are initialized to their zero values for the respective types.

user2 := User{
  Username: "bob",
}
Enter fullscreen mode Exit fullscreen mode

In this example, Email will be initialized to an empty string (""), SignInCount to 0, and IsActive to false.

Initializing with a Pointer

A struct can also be initialized using a pointer.

user3 := &User{
  Username: "charlie",
  Email:    "charlie@example.com",
}
Enter fullscreen mode Exit fullscreen mode

Methods and Behavior of Structs

In Go, structs are not only for storing data but can also have methods defined for them. This enables structs to encapsulate behavior related to their data. Below is a detailed explanation of struct methods and behavior.

Defining Methods for Structs

Methods are defined using a receiver, which is the first parameter of the method and specifies the type the method belongs to. The receiver can be either a value receiver or a pointer receiver.

Value Receiver

A value receiver creates a copy of the struct when the method is called, so modifications to fields do not affect the original struct.

type User struct {
  Username string
  Email    string
}

func (u User) PrintInfo() {
  fmt.Printf("Username: %s, Email: %s\n", u.Username, u.Email)
}
Enter fullscreen mode Exit fullscreen mode

Pointer Receiver

A pointer receiver allows the method to modify the original struct fields directly.

func (u *User) UpdateEmail(newEmail string) {
  u.Email = newEmail
}
Enter fullscreen mode Exit fullscreen mode

Method Sets

In Go, all methods of a struct form its method set. The method set for a value receiver includes all methods with value receivers, while the method set for a pointer receiver includes all methods with both pointer and value receivers.

Interfaces and Struct Methods

Struct methods are often used with interfaces to achieve polymorphism. When defining an interface, you specify the methods a struct must implement.

type UserInfo interface {
  PrintInfo()
}

// User implements the UserInfo interface
func (u User) PrintInfo() {
  fmt.Printf("Username: %s, Email: %s\n", u.Username, u.Email)
}

func ShowInfo(ui UserInfo) {
  ui.PrintInfo()
}
Enter fullscreen mode Exit fullscreen mode

Memory Alignment in Structs

In Go, memory alignment for structs is designed to improve access efficiency. Different data types have specific alignment requirements, and the compiler may insert padding bytes between struct fields to meet these requirements.

What is Memory Alignment?

Memory alignment means that data in memory must be located at addresses that are multiples of certain values. The size of a data type determines its alignment requirement. For example, int32 requires alignment to 4 bytes, and int64 requires alignment to 8 bytes.

Why is Memory Alignment Necessary?

Efficient memory access is critical for CPU performance. If a variable is not properly aligned, the CPU may need multiple memory accesses to read or write data, leading to performance degradation. By aligning data, the compiler ensures efficient memory access.

Rules for Struct Memory Alignment

  • Field alignment: Each field's address must meet its type's alignment requirements. The compiler may insert padding bytes between fields to ensure proper alignment.
  • Struct alignment: The size of a struct must be a multiple of the largest alignment requirement among its fields.

Example:

package main

import (
  "fmt"
  "unsafe"
)

type Example struct {
  a int8   // 1 byte
  b int32  // 4 bytes
  c int8   // 1 byte
}

func main() {
  fmt.Println(unsafe.Sizeof(Example{}))
}
Enter fullscreen mode Exit fullscreen mode

Output: 12

Analysis:

  • a is int8, occupying 1 byte, aligned to 1.
  • b is int32, requiring alignment to 4 bytes. The compiler inserts 3 padding bytes between a and b to align b's address to 4.
  • c is int8, requiring 1 byte, but the struct's total size must be a multiple of 4 (the largest alignment requirement). The compiler adds 3 padding bytes at the end.

Optimizing Memory Alignment

You can rearrange struct fields to minimize padding and reduce memory usage.

type Optimized struct {
  b int32  // 4 bytes
  a int8   // 1 byte
  c int8   // 1 byte
}
Enter fullscreen mode Exit fullscreen mode

Output: 8

In this optimized version, b is placed first, aligning it to 4 bytes. a and c are placed consecutively, making the total size 8 bytes, which is more compact than the unoptimized version.

Summary

  • Struct fields in Go are allocated memory based on their alignment requirements, with potential padding bytes.
  • Adjusting the order of fields can minimize padding and optimize memory usage.
  • Use unsafe.Sizeof to determine the actual memory size of a struct.

Nested Structs and Composition

In Go, nested structs and composition are powerful tools for code reuse and organizing complex data. Nested structs allow a struct to include another struct as a field, enabling the creation of complex data models. Composition, on the other hand, creates new structs by including other structs, facilitating code reuse.

Nested Structs

Nested structs enable one struct to include another struct as a field. This makes data structures more flexible and organized. Here's an example of a nested struct:

package main

import "fmt"

// Define the Address struct
type Address struct {
  City    string
  Country string
}

// Define the User struct, which includes the Address struct
type User struct {
  Username string
  Email    string
  Address  Address // Nested struct
}

func main() {
  // Initialize the nested struct
  user := User{
    Username: "alice",
    Email:    "alice@example.com",
    Address: Address{
      City:    "New York",
      Country: "USA",
    },
  }

  // Access fields of the nested struct
  fmt.Printf("User: %s, Email: %s, City: %s, Country: %s\n", user.Username, user.Email, user.Address.City, user.Address.Country)
}
Enter fullscreen mode Exit fullscreen mode

Struct Composition

Composition allows multiple structs to be combined into a new struct, enabling code reuse. In composition, a struct can include multiple other structs as fields. This helps build more complex models and share common fields or methods. Here's an example of struct composition:

package main

import "fmt"

// Define the Address struct
type Address struct {
  City    string
  Country string
}

// Define the Profile struct
type Profile struct {
  Age int
  Bio string
}

// Define the User struct, which composes Address and Profile
type User struct {
  Username string
  Email    string
  Address  Address // Composes the Address struct
  Profile  Profile // Composes the Profile struct
}

func main() {
  // Initialize the composed struct
  user := User{
    Username: "bob",
    Email:    "bob@example.com",
    Address: Address{
      City:    "New York",
      Country: "USA",
    },
    Profile: Profile{
      Age: 25,
      Bio: "A software developer.",
    },
  }

  // Access fields of the composed struct
  fmt.Printf("User: %s, Email: %s, City: %s, Age: %d, Bio: %s\n", user.Username, user.Email, user.Address.City, user.Profile.Age, user.Profile.Bio)
}
Enter fullscreen mode Exit fullscreen mode

Differences Between Nested Structs and Composition

  • Nested Structs: Used to combine structs together, where a field's type in one struct is another struct. This approach is often employed to describe data models with hierarchical relationships.
  • Composition: Allows a struct to include fields from multiple other structs. This method is used to achieve code reuse, enabling a struct to have more complex behaviors and attributes.

Summary

Nested structs and composition are powerful features in Go that help organize and manage complex data structures. When designing data models, using nested structs and composition appropriately can make your code clearer and more maintainable.

Empty Struct

An empty struct in Go is a struct with no fields.

Size and Memory Address

An empty struct occupies zero bytes of memory. However, its memory address may or may not be equal under different circumstances. When memory escape occurs, the addresses are equal, pointing to runtime.zerobase.

// empty_struct.go
type Empty struct{}

//go:linkname zerobase runtime.zerobase
var zerobase uintptr // Using the go:linkname directive to link zerobase to runtime.zerobase

func main() {
  a := Empty{}
  b := struct{}{}

  fmt.Println(unsafe.Sizeof(a) == 0) // true
  fmt.Println(unsafe.Sizeof(b) == 0) // true
  fmt.Printf("%p\n", &a)             // 0x590d00
  fmt.Printf("%p\n", &b)             // 0x590d00
  fmt.Printf("%p\n", &zerobase)      // 0x590d00

  c := new(Empty)
  d := new(Empty) // Forces c and d to escape
  fmt.Sprint(c, d)
  println(c)   // 0x590d00
  println(d)   // 0x590d00
  fmt.Println(c == d) // true

  e := new(Empty)
  f := new(Empty)
  println(e)   // 0xc00008ef47
  println(f)   // 0xc00008ef47
  fmt.Println(e == f) // false
}
Enter fullscreen mode Exit fullscreen mode

From the output, variables a, b, and zerobase share the same address, all pointing to the global variable runtime.zerobase (runtime/malloc.go).

Regarding escape scenarios:

  • Variables c and d escape to the heap. Their addresses are 0x590d00, and they compare equal (true).
  • Variables e and f have different addresses (0xc00008ef47) and compare unequal (false).

This behavior is intentional in Go. When empty struct variables do not escape, their pointers are unequal. After escaping, the pointers become equal.

Space Calculation When Embedding Empty Structs

An empty struct itself occupies no space, but when embedded in another struct, it might consume space depending on its position:

  • When it is the only field in the struct, the struct occupies no space.
  • When it is the first or intermediate field, it occupies no space.
  • When it is the last field, it occupies space equal to the previous field.
type s1 struct {
  a struct{}
}

type s2 struct {
  _ struct{}
}

type s3 struct {
  a struct{}
  b byte
}

type s4 struct {
  a struct{}
  b int64
}

type s5 struct {
  a byte
  b struct{}
  c int64
}

type s6 struct {
  a byte
  b struct{}
}

type s7 struct {
  a int64
  b struct{}
}

type s8 struct {
  a struct{}
  b struct{}
}

func main() {
  fmt.Println(unsafe.Sizeof(s1{})) // 0
  fmt.Println(unsafe.Sizeof(s2{})) // 0
  fmt.Println(unsafe.Sizeof(s3{})) // 1
  fmt.Println(unsafe.Sizeof(s4{})) // 8
  fmt.Println(unsafe.Sizeof(s5{})) // 16
  fmt.Println(unsafe.Sizeof(s6{})) // 2
  fmt.Println(unsafe.Sizeof(s7{})) // 16
  fmt.Println(unsafe.Sizeof(s8{})) // 0
}
Enter fullscreen mode Exit fullscreen mode

When empty structs are elements of arrays or slices:

var a [10]int
fmt.Println(unsafe.Sizeof(a)) // 80

var b [10]struct{}
fmt.Println(unsafe.Sizeof(b)) // 0

var c = make([]struct{}, 10)
fmt.Println(unsafe.Sizeof(c)) // 24, the size of the slice header
Enter fullscreen mode Exit fullscreen mode

Applications

The zero-size property of empty structs allows them to be used for various purposes without extra memory overhead.

Prevent Unkeyed Struct Initialization

type MustKeyedStruct struct {
  Name string
  Age  int
  _    struct{}
}

func main() {
  person := MustKeyedStruct{Name: "hello", Age: 10}
  fmt.Println(person)

  person2 := MustKeyedStruct{"hello", 10} // Compilation error: too few values in MustKeyedStruct{...}
  fmt.Println(person2)
}
Enter fullscreen mode Exit fullscreen mode

Implementing a Set Data Structure

package main

import (
  "fmt"
)

type Set struct {
  items map[interface{}]emptyItem
}

type emptyItem struct{}

var itemExists = emptyItem{}

func NewSet() *Set {
  return &Set{items: make(map[interface{}]emptyItem)}
}

func (set *Set) Add(item interface{}) {
  set.items[item] = itemExists
}

func (set *Set) Remove(item interface{}) {
  delete(set.items, item)
}

func (set *Set) Contains(item interface{}) bool {
  _, contains := set.items[item]
  return contains
}

func (set *Set) Size() int {
  return len(set.items)
}

func main() {
  set := NewSet()
  set.Add("hello")
  set.Add("world")
  fmt.Println(set.Contains("hello"))
  fmt.Println(set.Contains("Hello"))
  fmt.Println(set.Size())
}
Enter fullscreen mode Exit fullscreen mode

Signal Transmission via Channels

Sometimes, the content of the data transmitted through a channel is irrelevant, serving only as a signal. For instance, empty structs can be used in semaphore implementations:

var empty = struct{}{}

type Semaphore chan struct{}

func (s Semaphore) P(n int) {
  for i := 0; i < n; i++ {
    s <- empty
  }
}

func (s Semaphore) V(n int) {
  for i := 0; i < n; i++ {
    <-s
  }
}

func (s Semaphore) Lock() {
  s.P(1)
}

func (s Semaphore) Unlock() {
  s.V(1)
}

func NewSemaphore(N int) Semaphore {
  return make(Semaphore, N)
}
Enter fullscreen mode Exit fullscreen mode

We are Leapcell, your top choice for deploying Go projects to the cloud.

Leapcell

Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:

  1. Multi-Language Support
  • Develop with JavaScript, Python, Go, or Rust.
  1. Deploy unlimited projects for free
  • pay only for usage — no requests, no charges.
  1. Unbeatable Cost Efficiency
  • Pay-as-you-go with no idle charges.
  • Example: $25 supports 6.94M requests at a 60ms average response time.
  1. Streamlined Developer Experience
  • Intuitive UI for effortless setup.
  • Fully automated CI/CD pipelines and GitOps integration.
  • Real-time metrics and logging for actionable insights.
  1. Effortless Scalability and High Performance
  • Auto-scaling to handle high concurrency with ease.
  • Zero operational overhead — just focus on building.

Explore more in the Documentation!

Follow us on X: @LeapcellHQ


Read on our blog

Top comments (0)