Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.
Example 1:
package main
import (
"fmt"
)
type Student struct {
name string
marks int64
age int64
}
func(std *Student) fill_defaults(){
if std.name == "" {
std.name = "ABC"
}
if std.marks == 0 {
std.marks = 40
}
if std.age == 0 {
std.age = 18
}
}
func main() {
std1 := Student{name: "Vani" }
fmt.Println(std1)
std1.fill_defaults()
fmt.Println(std1)
std2 := Student{age: 19, marks: 78}
std2.fill_defaults()
fmt.Println(std2)
}
|
Output:
{Vani 0 0}
{Vani 40 18}
{ABC 78 19}
Another way of assigning default values to structs is by using tags. Tags can only be used for string values only and can be implemented by using single quotes(”).
Example 2:
package main
import (
"fmt"
"reflect"
)
type Person struct {
name string ` default : "geek" `
}
func default_tag(p Person) string {
typ := reflect.TypeOf(p)
if p.name == "" {
f, _ := typ.FieldByName( "name" )
p.name = f.Tag.Get( "default" )
}
return fmt.Sprintf( "%s" , p.name)
}
func main(){
fmt.Println( "Default name is:" , default_tag(Person{}))
}
|
Output:
Default name is: geek
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Jun, 2020
Like Article
Save Article