Зміст курсу
Introduction to GoLang
Introduction to GoLang
Data 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
:
index
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:
index
student1.name = "Leo"
Therefore, we can modify the program above to store some initial data accordingly:
index
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.
Дякуємо за ваш відгук!