Structs In Go

Structs In Go

A struct in Go is a collection of data fields that are useful for creating records of grouped data types. It can be thought of as a class variable in object-oriented programming.

The fields of a struct can be accessed using dot notation, for example

type Person struct {
  Name string
  Age int
}

person:= Person{
  Name: "John Doe",
  Age: 30,
}

fmt.Println(person.Name) // John Doe
fmt.Println(person.Age) // 30

Structs are a powerful tool for representing data in Go. They can be used to model real-world entities, such as people, products, or animals. Structs can also be used to pass data between functions and to store data in collections, such as slices and maps.

A struct pointer in Go is a variable that references the memory location of an instance of a struct type. It can be used to access the fields of the struct, just like a regular struct variable. However, a struct pointer can also be used to modify the values of the struct's fields.

To create a struct pointer, you can use the &structInstance operator to take the address of a struct variable. For example:

type Person struct {
  Name string
  Age int
}

person:= Person{
  Name: "John Doe",
  Age: 30,
}

personPtr := &person

Once you have a struct pointer, you can access the fields of the struct using dot notation, just like you would with a regular struct variable. For example:

personPtr.Name = "Jane Doe"
personPtr.Age = 31

You can also use a struct pointer to modify the values of the struct's fields. For example:

personPtr.Name = "Jane Doe"
personPtr.Age = 31

When you modify the values of the struct's fields using a struct pointer, the changes will be reflected in the original struct variable. This is because the struct pointer is simply a reference to the struct variable's memory location.

Structs can be initialized using the struct literal, which is a shorthand way of creating a new struct instance and assigning values to its fields. The syntax for a struct literal is:

var V structName{value1, value2, ...}

For example, the following code creates a new struct instance of type Person and assigns the values "John Doe" and 30 to the Name and Age fields, respectively:

type Person struct {
  Name string
  Age int
}

var person struct {
  Name string
  Age int
}{
  Name: "John Doe",
  Age: 30,
}

Note that the struct literal can omit any fields that are not being initialized. In this case, the Address field will be implicitly initialized to its zero value, which is the empty string for a string field and 0 for an int field.

It is also idiomatic to use a function to handle struct initialization. This function can take the values of the struct's fields as input and return a pointer to the newly initialized struct instance. For example, the following function creates a new struct instance of type Person and assigns the values passed to the function to the Name and Age fields:

func structConstructor(field1val string, field2val int) *Person {
  // creates an instance of the struct
  person := Person{
    Name: field1val,
    Age: field2val,
  }

  // return a pointer to the struct instance
  return &person
}

This function can then be used to initialize struct instances as needed. For example, the following code creates a new struct instance of type Person and assigns the values "Jane Doe" and 31 to the Name and Age fields, respectively:

person := structConstructor("Jane Doe", 31)

Anonymous Structs

In Golang, structs can be defined without a name, which is known as an anonymous struct. Anonymous structs are created using the struct literal syntax, but without a type name. For example:

House := struct {
  houseNo int
  Street string
}{
  12,
  "Yelwa"
}

Anonymous structs can be used to group data together without having to define a new struct type. They can also be used to pass data to functions or return data from functions.

Here are some more examples of anonymous structs:

// Create an anonymous struct with two fields.
data := struct {
  name string
  age int
}{
  "John Doe",
  30,
}

// Create an anonymous struct with one field.
price := struct {
  amount float64
}{
  123.45,
}

// Create an anonymous struct with no fields.
empty := struct{}{}

Anonymous structs can also be used to create struct literals with multiple instances of the same struct type. For example:

// Create a struct literal with three instances of the `Person` struct type.
people := []struct {
  name string
  age int
}{
  {"John Doe", 30},
  {"Jane Doe", 25},
  {"Peter Doe", 40},
}

Anonymous structs can be a useful way to group data and pass it to functions or return it from functions. They can also be used to create struct literals with multiple instances of the same struct type.

Struct Tags

In Golang, struct tags are annotations that appear after the struct type in a struct definition. They are short strings that represent a corresponding value and are enclosed with backticks.

For example, the following code defines a struct with a single field, Name, and a struct tag, maxLen, which specifies the maximum length of the Name field:

type User struct {
  Name string `maxLen:"20"`
}

Struct tags can be used to provide additional data when defining a struct field, such as the field's name, type, and length. This data can then be used by creating functions to read the tag and manipulate the information accordingly.

For example, the following function reads the maxLen tag for the Name field and prints an error message if the value of the Name field is longer than 20 characters:

func validateUser(user User) {
  // Get the value of the `maxLen` tag for the `Name` field.
  maxLength, err := strconv.Atoi(user.Name.Tag("maxLen"))
  if err != nil {
    fmt.Println("Error parsing struct tag:", err)
    return
  }

  // Check if the value of the `Name` field is longer than the maximum length.
  if len(user.Name) > maxLength {
    fmt.Println("The value of the `Name` field is too long.")
    return
  }
}

Struct tags can be a useful way to provide additional information about struct fields. This information can then be used by functions to validate data or to manipulate data in other ways.

Conclusion

  • Structs are a powerful tool for representing data in Golang.

  • They can be used to model real-world entities, such as people, products, or animals.

  • Struct is a collection of data fields which are useful for creating records of grouped data types.

  • These fields can be accessed using dot notation.

  • A struct pointer is a variable which references the memory location of an instance of a struct type.

  • Single or multiple fields can be directly referred to during initialisation, with the non-initialized fields being implicitly initialized as a zero value.

  • Struct tags are used to provide additional data when defining a struct field.

go.dev/tour/moretypes/2

gobyexample.com/structs

youtube.com/watch?v=NMTN543WVQY