create instances of a struct with a field in go

You can create instances of a struct in Go using the type and struct keywords. Here's an example of a struct with a field and how to create an instance of it:

main.go
type Person struct {
    Name string
}

func main() {
    // Creating an instance of the struct with Name field
    p := Person{
        Name: "Bob",
    }

    // Accessing the field of the struct
    fmt.Println(p.Name) // Output: "Bob"
}
241 chars
14 lines

In this example, we declare a Person struct with a Name field of type string. We then create an instance of the struct p using literal syntax and assign "Bob" to the Name field. After that, we access the Name field of the struct by calling p.Name and print "Bob" to the console using fmt.Println().

related categories

gistlibby LogSnag