by Timur Dautov

Understanding Structs in Golang

In Golang, a struct is a composite data type that groups together variables (called fields) under a single name.

Structs are used to create custom data types that can represent real-world entities or complex data structures.

Each field in a struct has a name and a type, and the fields can be of any valid Go type, including other structs.

Define a Struct#

To define a struct in Golang, use the type keyword followed by the struct name and the list of fields enclosed in curly braces {}.

type User struct {
    Name    string
    Age     int
    Address string
}

In this example:

  • User is the name of the struct.
  • Name, Age, and Address are the fields of the struct, with their respective types (string, int, and string).

Create an Instance of a Struct#

To create an instance of a struct, use the var keyword followed by the struct name and the field values enclosed in curly braces {}.

var user1 User
user1 = User{
    Name:    "Alice",
    Age:     30,
    Address: "123 Main St",
}

Here, user1 is an instance of the User struct with the specified field values.

Accessing Struct Fields#

To access the fields of a struct, use the dot . operator followed by the field name.

fmt.Println(user1.Name)    // Output: Alice
fmt.Println(user1.Age)     // Output: 30
fmt.Println(user1.Address) // Output: 123 Main St

This will print the values of the fields Name, Age, and Address of the user1 struct instance.

Nested Structs#

Structs can contain other structs as fields. This is useful for modeling more complex data structures.

type Address struct {
    City  string
    State string
}

type Person struct {
    Name    string
    Age     int
    Address Address
}

p := Person{
    Name: "Alice",
    Age:  30,
    Address: Address{
        City:  "New York",
        State: "NY",
    },
}
fmt.Println(p.Address.City)  // Output: New York

In this example, the Person struct contains an Address struct as a field. The Address struct has two fields: City and State.

Anonymous Structs#

An anonymous struct is a struct without a name. It is defined and instantiated in a single line.

person := struct {
    Name string
    Age  int
}{
    Name: "Bob",
    Age:  25,
}

In this example, we define an anonymous struct with fields Name and Age and create an instance of it with the specified field values.

Summary#

Structs are a fundamental concept in Golang that allows you to define custom data types by grouping together variables under a single name. They are used to represent real-world entities or complex data structures in a concise and readable way.