How to Assign Default Value for Struct Field in Golang?


In Golang, it is common to have struct types that need to be initialized with default values. In this article, we will explore how to assign a default value for a struct field in Golang.

Assigning Default Values for Struct Fields

To assign a default value for a struct field in Golang, we can define a default value for the field during the struct type declaration. For example, consider the following struct type −

type Person struct {
   Name    string
   Age     int
   Address string
}

In this struct, there is no default value assigned for any of the fields. To assign default values, we can define a constructor function that returns a new instance of the struct with default values assigned −

func NewPerson() Person {
   return Person{
      Name:    "John Doe",
      Age:     30,
      Address: "123 Main St",
   }
}

In this example, we define a NewPerson() function that returns a new instance of the Person struct with default values assigned. If the caller of the function does not provide a value for any of the fields, the default values will be used.

We can also assign default values for specific fields of the struct by defining the default value for that field in the struct type declaration. For example −

type Person struct {
   Name    string  `default:"John Doe"`
   Age     int     `default:"30"`
   Address string  `default:"123 Main St"`
}

In this example, we define a Person struct with default values assigned for each field using struct field tags. The default tag specifies the default value for each field. We can then use reflection to set the default value for a field if the field is not provided by the caller of the constructor function.

Using a constructor function to assign default values for struct fields is a common pattern in Golang. It allows us to define default values for struct fields in a centralized location and ensures that all instances of the struct are initialized with the same default values.

Example

package main

import (
   "fmt"
   "reflect"
   "strconv"
)

type Person struct {
   Name    string  `default:"John Doe"`
   Age     int     `default:"30"`
   Address string  `default:"123 Main St"`
}

func NewPerson() Person {
   p := Person{}
   setDefaults(&p)
   return p
}

func setDefaults(p *Person) {
   // Iterate over the fields of the Person struct using reflection
   // and set the default value for each field if the field is not provided
   // by the caller of the constructor function.
   for i := 0; i < reflect.TypeOf(*p).NumField(); i++ {
      field := reflect.TypeOf(*p).Field(i)
      if value, ok := field.Tag.Lookup("default"); ok {
         switch field.Type.Kind() {
            case reflect.String:
               if p.Name == "" {
                  p.Name = value
               }
            case reflect.Int:
               if p.Age == 0 {
                  if intValue, err := strconv.Atoi(value); err == nil {
                     p.Age = intValue
                  }
               }
         }
      }
   }
}

func main() {
   p := NewPerson()
   fmt.Println(p)
}

Output

{John Doe 30 }

Conclusion

Assigning default values for struct fields in Golang can be achieved by defining a constructor function that returns a new instance of the struct with default values assigned or by using struct field tags to assign default values for specific fields. This pattern ensures that all instances of the struct are initialized with the same default values, which can simplify code maintenance and reduce the likelihood of bugs.

Updated on: 19-Apr-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements