Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Declaring Structs in Go Programming

Introduction to Structs

In Go, a struct is a composite data type that groups together variables under a single name. These variables are called fields. Structs are useful for grouping data to form records. Each field within a struct can have a different data type.

Basic Declaration

To declare a struct, you use the type keyword followed by the name of the struct and the struct keyword. The fields of the struct are enclosed in curly braces.

type Person struct {
    Name string
    Age  int
}

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

Creating an Instance of a Struct

Once a struct is declared, you can create an instance of it. You can do this by using the struct type name followed by curly braces containing the field values.

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

Here, we have created an instance p of the Person struct and assigned values to its fields.

Accessing and Modifying Struct Fields

You can access and modify the fields of a struct instance using the dot (.) operator.

fmt.Println(p.Name) // Output: John
p.Age = 31
fmt.Println(p.Age) // Output: 31

In this example, we accessed the Name field of p and printed it. We then modified the Age field and printed it.

Anonymous Structs

Go also supports anonymous structs, which are useful when you want to define a one-off struct without declaring a new type.

student := struct {
    Name  string
    Grade int
}{
    Name: "Alice",
    Grade: 90,
}

In this example, we have declared an anonymous struct with fields Name and Grade and created an instance of it.

Nested Structs

Structs in Go can be nested, meaning a struct can have fields that are themselves structs.

type Address struct {
    City    string
    ZipCode int
}

type Employee struct {
    Name    string
    Address Address
}

In this example, we have declared an Address struct and an Employee struct that contains an Address field.

Example: Declaring and Using Structs

Let's put everything together in a complete example. We'll declare a struct, create an instance of it, and access its fields.

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "John", Age: 30}
    fmt.Println("Name:", p.Name)
    fmt.Println("Age:", p.Age)
    p.Age = 31
    fmt.Println("Updated Age:", p.Age)
}

In this example, we declared a Person struct, created an instance of it, and accessed and modified its fields.

Name: John
Age: 30
Updated Age: 31