create instances of a struct with multiple fields in go

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.go
type Person struct {
    Name   string
    Age    int
    Gender string
}
74 chars
6 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.go
p := Person{Name: "John", Age: 30, Gender: "Male"}
51 chars
2 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.go
p := Person{Name: "Jane", Age: 25}
35 chars
2 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.go
fmt.Println(p.Name)    // Output: John
fmt.Println(p.Age)     // Output: 30
fmt.Println(p.Gender)  // Output: Male
115 chars
4 lines

This prints the values of the fields of the p variable.

gistlibby LogSnag