Structs
- The data types created by the programmer.
- A collection of key-value pairs.
- All the keys in a struct don't need to be in the same data type.
type Employee struct {
Name string
Age int
Job string
}
Data types of keys can also be structs (not primitive datatypes). As you can see in the below example the DepartmentHead
is of type Employee
.
type Department struct {
DepartmentName string
DepartmentLocation string
DepartmentHead Employee
}
Struct usage
The syntax of struct initialization is given below.
deptHead := Employee{}
You can access the keys of a struct by using the dot operator. It is also used to assign values to the keys.
deptHead.Name = "Edward Cullen"
deptHead.Age = 17
deptHead.Job = "Department Head"
Anonymous structs
In Go, we can define structs without giving them a name. It is used only when you do not need several instances of a struct. An example is given below.
user := struct {
name string
age int
job string
} {
name: "Bella",
age: 11,
job: "Writer",
}
Also, note that using unnamed structs is not that much common.
Nested structs
We can have structs inside a struct. And the inserted struct can be anonymous.
type Department struct {
DepartmentName string
DepartmentLocation string
DepartmentHead struct {
Name string
Age int
Job string
}
}
For clean code use named structs whenever possible.
Embedded structs
Embedded structs are different from nested structs. Here, you don't use a key-value pair inside the main struct. Look at the given example.
type deptHead struct {
Name string
Age int
Job string
}
type Department struct {
DepartmentName string
DepartmentLocation string
deptHead
}
The struct deptHead
is directly embedded in the Department
struct without any key (field). Therefore, Department
inherits all the features of deptHead
directly. So, you can access Name
directly from a Department
instance (Department.Name
).
Even though I have used the word inheritance above, please note that Golang is NOT an object-oriented language. It doesn't suppose classes or inheritance.
The fields of an embedded struct are accessed at the top level unlike in nested structs.
dept := Department{
DepartmentName: "wearwolf",
DepartmentLocation: "seattle",
deptHead: deptHead{
Name: "Jcob",
Age: 16,
Job: "Department head",
},
}
fmt.Printf("Department head is %s", dept.Name)
If you check the print statement in the above example, we have accessed the name of the department head directly. We can use dept.Name
instead of dept.deptHead.Name
when using embedded structs.
Struct Methods
We can define methods (functions) on structs. You can initialize a struct and then use dot operator to access its methods. Check out the example below.
type rectangle struct {
lenght int
width int
}
func (r rectangle) getArea() int {
return r.lenght * r.width
}
func main() {
r := rectangle {
lenght: 10,
width: 5,
}
area := r.getArea() // calling method using dot operator
fmt.Printf("Area of r: %d", area)
}