create instances of a struct in go

In Go programming language, we use structs to define custom data types. In order to create instances of these data types, we can use the new() keyword.

Here's an example of creating an instance of a struct in Go:

main.go
type Person struct {
    name string
    age int
}

func main() {
    // Creating instance of the Person struct using new()
    p := new(Person)
    
    // Assigning values to the fields
    p.name = "John"
    p.age = 30
    
    // Printing the values of the fields
    fmt.Println(p.name, "is", p.age, "years old.")
}
322 chars
17 lines

In this example, we defined a struct Person with two fields, name and age. We then created a new instance of this struct using the new() keyword. Since new() returns a pointer to the newly allocated zero value of the struct, we assigned the returned value to a variable p.

We then assigned values to the fields of p and printed them out.

Output:

main.go
John is 30 years old.
22 chars
2 lines

gistlibby LogSnag