Go Structs
What is a Struct?
Structs (short for structure) are custom data types you create yourself. Structs are composed of properties, each with a built-in data type.
Why use Structs?
Arrays and slices are useful for storing values for the same thing, like the number of students in each class, but arrays and slices are bad for storing values that represent different things. To overcome this issue, we use structs.
Making a Struct
Structs are in the following form:
type struct_name struct {
member1 datatype
member2 datatype
member3 datatype
}
For example, we could have:
type CollegeStudent struct {
firstName string
lastName string
major string
birthYear int
}
Using a Struct
Below is an example of using the CollegeStudent
struct we created earlier:
var student1 CollegeStudent
var student2 CollegeStudent
student1.firstName = "Aaron"
student1.lastName = "Hou"
student1.major = "Computer Science"
student1.birthYear = 2006
student2.firstName = "Isaac"
student2.lastName = "Shaul"
student2.major = "Art History"
student2.birthYear = 2000