Struct
In Go, a struct is a collection of fields. Each field has a name and a type. Fields are also known as members of a struct. A struct can be defined using the struct
keyword, followed by a list of fields enclosed in curly braces. Here's an example of a struct that represents a rectangle:
type Rectangle struct {
width float64
height float64
}
You can create a new instance of a struct by using the new
keyword, or by initializing the fields directly. Here's an example of both:
// using the new keyword
r := new(Rectangle)
// initializing fields directly
r := Rectangle{width: 10, height: 20}
You can also create a struct using a struct literal, which is similar to an object literal in JavaScript. Here's an example:
r := Rectangle{10, 20}
You can access the fields of a struct using dot notation. For example, you can get the width of a rectangle by calling r.width
. You can also change the values of the fields by assigning a new value to them. Here's an example:
// getting the width of a rectangle
fmt.Println(r.width)
// changing the value of the width field
r.width = 15
It is also possible to define methods on structs, which are functions that operate on the struct's fields. Here's an example of a method that calculates the area of a rectangle:
func (r *Rectangle) Area() float64 {
return r.width * r.height
}
You can call this method by using the dot notation on an instance of the struct, like this:
area := r.Area()
It is also possible to define a function that takes a struct as an argument, like this:
func doubleWidth(r *Rectangle) {
r.width = r.width * 2
}
You can call this function and pass an instance of the struct as an argument, like this:
doubleWidth(&r)
You can also define a struct that has another struct as one of its fields, which is called a nested struct or embedded struct
type Person struct {
Name string
Age int
}
type Employee struct {
Person
Salary int
}
You can use an embedded struct to access its fields without needing to use the dot notation.
e := Employee{Person{"John", 30}, 5000}
fmt.Println(e.Name, e.Age, e.Salary)
Last updated