Sling Academy
Home/Golang/Defining and Initializing Structs in Go: A Beginner's Guide

Defining and Initializing Structs in Go: A Beginner's Guide

Last updated: November 26, 2024

Structs are custom data types in Go that allow you to group together variables of different types under a single type. They are similar to classes in object-oriented programming languages but are simpler and do not provide inheritance, methods, or constructors.

Defining Structs

To define a struct in Go, use the type keyword followed by the struct name and keyword struct. Structs are defined at the package level, allowing them to be used across multiple functions within the same package.

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

In this example, a struct named Person is defined with two fields: Name of type string, and Age of type int.

Basic Initialization

After defining a struct, initializing it can be done using field names within a struct literal.

func main() {
    // Initializing a Person struct
    bob := Person{
        Name: "Bob",
        Age:  25,
    }
    fmt.Println(bob)
}

This initializes a Person instance with the name "Bob" and age 25.

Intermediate Struct Initialization without Field Names

Go also supports initializing a struct without specifying field names. Fields are initialized in the order they are defined in the struct.

func main() {
    // Initializing a Person struct without field names
    alice := Person{"Alice", 30}
    fmt.Println(alice)
}

Note that using this method of initialization can make your code less readable, especially as the number of fields in the struct increases.

Pointers and Structs

Like any other data type, you can create a pointer to a struct using the & operator.

func main() {
    // Using a pointer to intern a struct
    p := &Person{Name: "Charlie", Age: 28}
    fmt.Println(p)
}

Pointers are especially useful when you want to modify the struct data without copying it and when structures are large, helping with efficient memory use.

Advanced Structs: Embedded Structs

Go supports embedded structs, allowing you to compose and reuse struct types.

type Address struct {
    City   string
    State  string
}

type Contact struct {
    Person  // Embedded struct
    Email   string
    Address // Embedded struct
}

func main() {
    john := Contact{
        Person: Person{Name: "John", Age: 35},
        Email:  "[email protected]",
        Address: Address{
            City:  "Citysville",
            State: "Stateland",
        },
    }
    fmt.Println(john)
}

An embedded struct allows you to directly access fields of the embedded type. For example, you can access Name from john directly as john.Name.

Conclusion

Structs are a powerful way to create complex data types in Go through composition rather than inheritance. With this guide, you should be able to define, initialize, and manipulate structs in Go comfortably.

Next Article: Using Structs to Model Real-World Entities in Go

Series: Structs and Interfaces in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant