Creating Structs
Up to this point, we've dealt with variables of various basic data types, such as int, float32, string, and so on. However, we have the capability to create new data types, which are essentially collections of other data types.
Structs, also known as structures, are essentially user-defined data types. Therefore, a struct can also sometimes be referred to as a data type.
In the image above, we have an illustration of a structure called Person
, which comprises fields of different data types, specifically name
, age
, and salary
. A structure itself serves as a blueprint that defines what data will be stored in an instance of its type. We can create an instance, essentially a variable, using the Person
data type, and then store a person's name, age, and salary within it.
Similarly, we can also create arrays using the Person
data type. Hence, structs are very useful when we want to store and access related data in an organized manner.
The following syntax is used for declaring a struct in code:
9123456type structName struct {element_1 datatypeelement_2 datatypeelement_3 datatype…}
Note
The terms
type
andstruct
are keywords in Golang.
Following the above syntax, we can implement the example of the Person
struct, which was discussed above:
Following is another slightly more complicated example that contains an array as well:
index.go
1234567type Student struct { name string age int id int course string grades [5]float32 }
In the example above, there's a field called grades
, which is an array of size 5
and type float32
. We will learn in the following chapters how to store, access, and modify struct data.
We can also reference other structs (custom data types) within the definition of structs. For instance, the Course
struct includes a field called students
, which is a slice of type Student
:
index.go
1234type Course struct { name string students []Student }
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår