To create instances of a struct with multiple fields in Go, you first need to define the struct type with its fields. For example:
main.go74 chars6 lines
This defines a struct type called Person
with three fields: Name
, Age
, and Gender
.
To create an instance of this struct, you can do the following:
main.go51 chars2 lines
This creates a new variable p
of type Person
and initializes its fields with the given values. You can also create an instance with some fields initialized and others set to their default values like this:
main.go35 chars2 lines
Here, the Gender
field is not provided, so Go initializes it to its default value, which is an empty string.
You can access the fields of a struct variable using the dot notation, like this:
main.go115 chars4 lines
This prints the values of the fields of the p
variable.
gistlibby LogSnag