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

Contenido del Curso

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

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

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:

go

index

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

go

index

copy
1234
type Course struct { name string students []Student }
What is the correct syntax for declaring a Struct with the name `myStruct`:

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

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 6. Capítulo 1
We're sorry to hear that something went wrong. What happened?
some-alt