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:
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:
You can also create a struct using a struct literal, which is similar to an object literal in JavaScript. Here's an example:
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:
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:
You can call this method by using the dot notation on an instance of the struct, like this:
It is also possible to define a function that takes a struct as an argument, like this:
You can call this function and pass an instance of the struct as an argument, like this:
You can also define a struct that has another struct as one of its fields, which is called a nested struct or embedded struct
You can use an embedded struct to access its fields without needing to use the dot notation.
Last updated