Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Creating Structs | Intro to Structs & Maps
Introduction to GoLang

book
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:

type structName struct {
element_1 datatype
element_2 datatype
element_3 datatype
}

Note

The terms type and struct 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

index.go

copy
type Student struct {
name string
age int
id int
course string
grades [5]float32
}
1234567
type 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

index.go

copy
type Course struct {
name string
students []Student
}
1234
type Course struct { name string students []Student }
question mark

What is the correct syntax for declaring a Struct with the name myStruct:

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 6. Kapittel 1

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt