create a struct with multiple fields in go

In Go, you can create a struct with multiple fields by defining a new type using the type keyword, and specifying each field using its name and data type.

Here's an example of how to create a struct with two fields, name and age:

main.go
type Person struct {
    name string
    age int
}
51 chars
5 lines

In this example, we've created a new type Person, which has two fields: name of type string, and age of type int.

To create a new Person object and initialize its fields, you can simply use the Person{} syntax and provide values for each field:

main.go
p := Person{name: "John", age: 30}
35 chars
2 lines

This will create a new Person object p with the name field equal to "John" and the age field equal to 30.

You can access the fields of a struct using the dot (.) operator:

main.go
fmt.Println(p.name) // Output: John
fmt.Println(p.age) // Output: 30
69 chars
3 lines

I hope this helps you create your own structs with multiple fields in Go!

related categories

gistlibby LogSnag