...

/

Introduction to Struct

Introduction to Struct

This lesson introduces structs, addressing rudimentary concepts such as declaration and memory allocation.

Go supports user-defined or custom types in the form of alias types or structs. A struct tries to represent a real-world entity with its properties. Structs are composite types to use when you want to define a type that consists of several properties each having their type and value, grouping pieces of data together. Then, one can access that data as if it were part of a single entity.

Structs are value types and are constructed with the new function. The component pieces of data that constitute the struct type are called fields. A field has a type and a name. Field names within a struct must be unique.

The concept was called ADT (Abstract Data Type) in older texts on software engineering. It was also called a record in older languages like Cobol, and it also exists under the same name of struct in the C-family of languages and in the OO languages as a lightweight-class without methods.

However, because Go does not have the concept of a class, the struct type has a much more important place in Go.

Definition of a struct

The general format of the definition of a struct is as follows:

type identifier struct {
  field1 type1
  field2 type2
  ...
}

Also, type T struct { a, b int } is legal syntax and is more suited for simple structs. The fields in this struct have names, like field1, field2, and so on. If the field is never used in code, it can be named _.

These fields can be of any type, even structs themselves, functions or interfaces. Because a struct is a value, we can declare a ...