How to Assign Default Value for Struct Field in Golang

To assign a default value for a field in the Golang struct, you use the “constructor function” or “struct tags” that initializes a new struct instance with default values.

Method 1: Using a constructor function

You can use a “constructor function” to assign default values to all or some struct fields.

Example

package main

import (
  "fmt"
)

// Define a struct with several fields
type MainStruct struct {
  FirstField string
  SecondField int
  ThirdField bool
}

// NewMainStruct is a constructor function that returns
// a new instance of MainStruct with default values
func NewMainStruct() *MainStruct {
  return &MainStruct{
    FirstField: "KHUSHI",
    SecondField: 19,
    ThirdField: true,
  }
}

func main() {
  myInstance := NewMainStruct()
 
  // Print the values of the struct fields
  fmt.Printf("FirstField: %s\n", myInstance.FirstField)
  fmt.Printf("SecondField: %d\n", myInstance.SecondField)
  fmt.Printf("ThirdField: %t\n", myInstance.ThirdField)
}

Output

FirstField: KHUSHI
SecondField: 19
ThirdField: true

In this example, we defined a struct called MainStruct with three fields. The constructor function NewMainStruct returns a new instance of MainStruct with default values for each field.

When creating an instance of MainStruct with default values, you can call NewMainStruct() instead of using the regular struct literal syntax.

Method 2: Using a struct tags

Another approach to assigning default values to structs is using “tags”. Tags can only be used for string values and can be implemented using single quotes(”).

Example

package main

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

type Student struct {
  Name string `default:"Krunal"`
  Grade int `default:"0"`
}

func setDefaultValues(s *Student) {
  v := reflect.ValueOf(s).Elem()
  t := v.Type()

  for i := 0; i < v.NumField(); i++ {
    field := v.Field(i)
    tag := t.Field(i).Tag.Get("default")

    if tag == "" {
      continue
    }

   switch field.Kind() {
     case reflect.String:
       if field.String() == "" {
         field.SetString(tag)
       }
     case reflect.Int:
       if field.Int() == 0 {
         if intValue, err := strconv.ParseInt(tag, 10, 64); err == nil {
           field.SetInt(intValue)
         }
       }
      // Add cases for other types if needed
    }
  }
}

func main() {
  student := Student{
    Name: "", // Leave empty to set default value
    Grade: 0, // Leave zero to set default value
  }

  setDefaultValues(&student)
  fmt.Printf("Student: %+v\n", student)
}

Output

Student: {Name:Krunal Grade:0}

The setDefaultValues() function checks if the field value is empty or zero (depending on the field’s type) and assigns the default value from the tag if necessary.

The main() function initializes a Student struct with empty values for the Name field and zero for the Grade field.

When we call the setDefaultValues() function with the Student struct, it sets the fields to their default values specified in the tags.

Leave a Comment