create a struct with a field in go

To create a struct with a field in Go, you can define a new type using the type keyword with the struct composition. You can then specify the fields for your struct and their data types like this:

main.go
type person struct {
  name string
  age int
  isMarried bool
}
64 chars
6 lines

Here, we defined a new type person that has 3 fields: name of type string, age of type int, and isMarried of type bool.

You can then create a new instance of the person struct and set its field values using the dot notation like this:

main.go
john := person{name: "John", age: 30, isMarried: false}
56 chars
2 lines

Now we have a new variable john of type person with the specified field values.

main.go
fmt.Println(john.name) // Output: John
fmt.Println(john.age) // Output: 30
fmt.Println(john.isMarried) // Output: false
120 chars
4 lines

You can also define methods on your struct to operate on its fields.

related categories

gistlibby LogSnag