How to initialise a struct in Go?

In Go, you can initialize a struct using several methods, depending on your requirements and the fields of the struct. Here are some common ways to initialize a struct:

  1. Literal Initialization: You can create and initialize a struct using a struct literal, where you explicitly specify the values for each field in the struct.
package main

import "fmt"

type Person struct {
    Name    string
    Age     int
    Country string
}

func main() {
    // Struct literal initialization
    person := Person{
        Name:    "John Doe",
        Age:     30,
        Country: "USA",
    }

    fmt.Println(person)
}
  1. Zero-Value Initialization: If you don’t explicitly initialize the struct fields, Go assigns their zero-values (e.g., numeric fields will be 0, string fields will be empty, etc.).
package main

import "fmt"

type Person struct {
    Name    string
    Age     int
    Country string
}

func main() {
    // Zero-value initialization
    var person Person
    fmt.Println(person)
}
  1. New Function: The new function allocates memory for a new zeroed struct and returns a pointer to it.
package main

import "fmt"

type Person struct {
    Name    string
    Age     int
    Country string
}

func main() {
    // New function initialization
    personPtr := new(Person)
    fmt.Println(*personPtr)
}
  1. Composite Literal Initialization: You can initialize a struct using a composite literal, which omits the field names and provides values in the order the fields are defined in the struct.
package main

import "fmt"

type Person struct {
    Name    string
    Age     int
    Country string
}

func main() {
    // Composite literal initialization
    person := Person{"John Doe", 30, "USA"}
    fmt.Println(person)
}

All of these methods are valid ways to initialize a struct in Go. The choice of method depends on your specific use case and preference. Struct literal initialization is commonly used when you want to explicitly set the values of specific fields, while the zero-value initialization and new function are used when you need a zeroed struct or a pointer to a zeroed struct, respectively. The composite literal initialization is useful when you want to initialize a struct in a compact manner without specifying field names.

error: Content is protected !!