Structs in Go

Go: Structs

In Go, a struct is a user-defined type that represents a collection of fields. Each field has a name and a type, and the fields are defined inside the curly braces that define the struct.

JSON to GO struct Converter

how to define a struct in Go:

    type Person struct {
        Name string
        Age int
        Email string
    }

In this example, we define a struct called Person that has three fields: Name (a string), Age (an integer), and Email (a string).

Create a new instance of struct

you can use the following syntax:

    p := Person{
        Name: "John Doe",
        Age: 30,
        Email: "johndoe@example.com",
    }

In this example, we create a new instance of the "Person" struct and initialize its fields with the values provided.

How to access the fields of a struct

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

    fmt.Println(p.Name)    // Output: John Doe
    fmt.Println(p.Age)     // Output: 30
    fmt.Println(p.Email)   // Output: johndoe@example.com

How to pass structs as parameters to functions

You can also pass structs as parameters to functions, and return structs from functions like below example

    func PrintPerson(p Person) {
        fmt.Println(p.Name, p.Age, p.Email)
    }

    func NewPerson(name string, age int, email string) Person {
        return Person{
            Name: name,
            Age: age,
            Email: email,
        }
    }

In these examples, we define a function called PrintPerson that takes a Person struct as a parameter and prints its fields, and a function called NewPerson that creates a new instance of the Person struct and returns it.

There are many more things you can do with structs, such as embedding one struct inside another, using methods to define behavior for a struct, and more. I encourage you to check out the official Go documentation for more details!

Previous Article