Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Structs in Go

What is a Struct?

In Go, a struct is a composite data type that groups together variables under a single name. These variables, known as fields, can have different types. Structs are particularly useful for representing complex data structures, such as records or objects.

Defining a Struct

To define a struct, use the type and struct keywords. Here is an example:

type Person struct {
    Name string
    Age  int
    City string
}
                

In this example, we define a struct named Person with three fields: Name (string), Age (int), and City (string).

Creating an Instance of a Struct

Once a struct type is defined, you can create instances of that struct. Here is how you can create and initialize a Person struct:

var p Person
p.Name = "Alice"
p.Age = 30
p.City = "New York"
                

You can also use a shorthand syntax to initialize a struct:

p := Person{
    Name: "Alice",
    Age:  30,
    City: "New York",
}
                

Accessing Struct Fields

You can access the fields of a struct using the dot notation:

fmt.Println(p.Name) // Outputs: Alice
fmt.Println(p.Age)  // Outputs: 30
fmt.Println(p.City) // Outputs: New York
                

Structs with Methods

Structs can have methods associated with them. Methods are functions that have a receiver argument. Here is an example of a method for the Person struct:

func (p Person) Greet() string {
    return "Hello, my name is " + p.Name
}
                

In this example, the Greet method returns a greeting message that includes the person's name.

Using Structs in Go Programs

Here is a complete example that demonstrates the creation and use of structs in a Go program:

package main

import "fmt"

type Person struct {
    Name string
    Age  int
    City string
}

func (p Person) Greet() string {
    return "Hello, my name is " + p.Name
}

func main() {
    p := Person{
        Name: "Alice",
        Age:  30,
        City: "New York",
    }
    
    fmt.Println(p.Greet())
}
                

When you run this program, it will output:

Hello, my name is Alice