Go struct
In Go, a struct is a composite data type that allows you to define your own custom data structures. A struct is a collection of fields, where each field has a name and a type. You can think of a struct as a template for creating objects that contain multiple fields of different types.
The syntax for defining a struct in Go is as follows:
type StructName struct { field1 type1 field2 type2 // ... }
Here's an example of defining a struct that represents a person:
type Person struct { Name string Age int }
In this example, a struct named Person
is defined with two fields: Name
of type string
and Age
of type int
.
You can create an instance of a struct by declaring a variable of the struct type and initializing its fields. Here's an example:
p := Person{Name: "Alice", Age: 30}
In this example, a new Person
struct is created and assigned to the variable p
. The Name
field is initialized to the string "Alice" and the Age
field is initialized to the integer 30.
You can access the fields of a struct using the dot (.
) operator. Here's an example:
fmt.Println(p.Name) fmt.Println(p.Age)
In this example, the Name
and Age
fields of the Person
struct p
are printed to the console.
You can also create a pointer to a struct using the &
operator, and dereference a pointer to a struct using the *
operator. Here's an example:
pPtr := &p fmt.Println((*pPtr).Name) fmt.Println((*pPtr).Age)
In this example, a pointer to the Person
struct p
is created and assigned to the variable pPtr
. The fields of the struct are then accessed using the *
operator.