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

Зміст курсу

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

bookData in Structs

Now that we know how to create an instance of a structure, we should learn how to store and modify data in them.

We can use the dot (.) symbol followed by the field name to reference it. Consider the example in the following program, where we create an instance of the Student class called student1:

go

index

copy
123456789101112131415161718192021
package main import "fmt" type Student struct { name string age int id int course string grades [5]float32 } func main() { var student1 Student fmt.Println("Name:", student1.name) fmt.Println("Age:", student1.age) fmt.Println("ID:", student1.id) fmt.Println("Course:", student1.course) fmt.Println("Grades:", student1.grades) }

This is because no data was manually stored in the structure, causing each of the fields to take a default zero value based on its type.

Note

In Go, we cannot specify our own default values for the fields; it automatically assigns zero values to the fields based on their types. However, we can specify custom default values by creating a constructor function, which is beyond the scope of this course as it requires knowledge of pointers.

We can also reference and assign values to the fields using the same referencing method, for example:

go

index

copy
1
student1.name = "Leo"

Therefore, we can modify the program above to store some initial data accordingly:

go

index

copy
123456789101112131415161718192021222324252627
package main import "fmt" type Student struct { name string age int id int course string grades [5]float32 } func main() { var student1 Student student1.name = "Leo" student1.age = 21 student1.id = 121 student1.course = "CS" student1.grades = [5] float32 { 4.5, 4.55, 4.49, 4.92, 5.0 } fmt.Println("Name:", student1.name) fmt.Println("Age:", student1.age) fmt.Println("ID:", student1.id) fmt.Println("Course:", student1.course) fmt.Println("Grades:", student1.grades) }

Note

The fields of a struct are also referred to as members.

Which symbol do we use for accessing the struct members / fields:

Which symbol do we use for accessing the struct members / fields:

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 6. Розділ 3
some-alt