Golang - Assign default values to a struct using tags Code Example

The code for Assign default values to a struct using tags

package main
  
import (
    "fmt"
    "reflect"
)
  
// person structure
type Person struct {
      name string `default:"Default_Name"` 
}

func default_tag(per Person) string {
      typ := reflect.TypeOf(per)
 
      if per.name == "" {
            f, _ := typ.FieldByName("name")
            per.name = f.Tag.Get("default")
      }
  
      return fmt.Sprintf("%s", per.name)
}
  
func main(){
    // printing the default name 
    fmt.Println("The default value of name is:", default_tag(Person{}))
}

/*
Output:
The default value of name is: Default_Name
*/
Code by IncludeHelp, on February 28, 2023 16:21

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.