Golang - Assign default values to a struct using constructor function Code Example

The code for Assign default values to a struct using constructor function

package main
  
import (
    "fmt"
)
  
// student structure
type Student struct{
    // variables
    name string
    marks int64
    age int64
}
  
// constructor function
func(std *Student) fill_defaults(){
    // default values
    if std.name == "" {
        std.name = "Default_Name"
    }
      
    if std.marks == 0 {
        std.marks = 33
    }
      
    if std.age == 0 {
        std.age = 21
    }
}
  
func main() {
    // Declaring structure object
    std1 := Student{name: "Pranit Sharma"}
    
    // printing
    fmt.Println(std1)
    
    // assigning default values
    std1.fill_defaults()
    
    // printing
    fmt.Println(std1)
    
    // assigning  values
    std2 := Student{age: 25, marks: 95}
    
    // assigning default values
    std2.fill_defaults()
    
    // printing
    fmt.Println(std2)
}

/*
Output:
{Pranit Sharma 0 0}
{Pranit Sharma 33 21}
{Default_Name 95 25}
*/
Code by IncludeHelp, on February 28, 2023 16:18

Comments and Discussions!

Load comments ↻






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