How to pass default parameter to golang function?


Tuan Nguyen

GO

Some programming languages (such as python) allow function arguments to have default values. If the function is called without the argument, the argument gets its default value. For example:

def name(firstname, lastname ='Mark', standard ='Fifth'):
     print(firstname, lastname, 'studies in', standard, 'Standard')
 
# 1 positional argument
name('John')
 
# 3 positional arguments                        
name('John', 'Gates', 'Seventh')    
 
# 2 positional arguments 
name('John', 'Gates')                 
name('John', 'Seventh')

Unfortunately, default arguments are not supported by Go. We still can have some other options to implement setting default value for function parameters. Let's look at the below example:

 

Example 1: Golang pass nil as an argument

In the below example, if the parameter is zero value , set it with the default value:

package main

import "fmt"

func main() {
	fmt.Println(GetStudentInfo("", ""))
	fmt.Println(GetStudentInfo("Anna", ""))
	fmt.Println(GetStudentInfo("", "+145366"))
}

func GetStudentInfo(name string, phoneNumber string) string {
	if name == "" {
		name = "default-name"
	}

	if phoneNumber == "" {
		phoneNumber = "default-phoneNumber"
	}

	return fmt.Sprintf("Name: %s, Phone number: %s", name, phoneNumber)
}

Output:

Name: default-name, Phone number: default-phoneNumber
Name: Anna, Phone number: default-phoneNumber
Name: default-name, Phone number: +145366

 

Example 2: Golang ... parameter in variadic functions

In the below section, we have an article about variadic functions. Here is an example of using the variadic functions to set a default value for parameters:

package main

import "fmt"

func main() {
	fmt.Println(GetStudentInfo2("Anna"))
	fmt.Println(GetStudentInfo2("Teddy", "+3688269"))
	fmt.Println(GetStudentInfo2("Adele", "+145366", "+58963144"))
}

// name is required, phoneNumber is optional. Only the first value in phoneNumber_optional can be used.
func GetStudentInfo2(name string, phoneNumber_optional ...string) string {
	phoneNumber := "default-phoneNumber"
	if len(phoneNumber_optional) > 0 {
		phoneNumber = phoneNumber_optional[0]
	}

	return fmt.Sprintf("Name: %s, Phone number: %s", name, phoneNumber)
}

Output:

Name: Anna, Phone number: default-phoneNumber
Name: Teddy, Phone number: +3688269
Name: Adele, Phone number: +145366

 

Example 3: Putting all params in a struct

Here is an example of using a struct as the parameter and we can set the default value for fields in the struct:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	fmt.Println(GetStudentInfo3(Param{"Anna", ""}))
	fmt.Println(GetStudentInfo3(Param{"Teddy", "+3688269"}))
	fmt.Println(GetStudentInfo3(Param{"", ""}))
}

type Param struct {
	Name        string `default:"default-name"` // setting default value for field
	PhoneNumber string `default:"default-phoneNumber"`
}

func GetStudentInfo3(prm Param) string {
	//type of interface value passed to it
	typ := reflect.TypeOf(prm)

	if prm.Name == "" {
		// returns the struct field with the given parameter "Name"
		f, _ := typ.FieldByName("Name")
		// get default value of Name field
		prm.Name = f.Tag.Get("default")
	}

	if prm.PhoneNumber == "" {
		f, _ := typ.FieldByName("PhoneNumber")
		prm.PhoneNumber = f.Tag.Get("default")
	}

	return fmt.Sprintf("Name: %s, Phone number: %s", prm.Name, prm.PhoneNumber)
}

Output:

Name: Anna, Phone number: default-phoneNumber
Name: Teddy, Phone number: +3688269
Name: default-name, Phone number: default-phoneNumber

 

Example 4: Using a map as the function parameter

Here is an example of using a map as the function parameter:

package main

import (
	"fmt"
	"reflect"
)

func main() {

	fmt.Println(GetStudentInfo4(map[string]interface{}{}))
	fmt.Println(GetStudentInfo4(map[string]interface{}{"Name": "Harry Potter"}))
	fmt.Println(GetStudentInfo4(map[string]interface{}{"Name": "Lady Gaga", "Age": 40}))
}

type varArgs map[string]interface{}

func GetStudentInfo4(args varArgs) string {

	name := "default-name"
	if val, ok := args["Name"]; ok {
		name = val.(string)
	}

	age := 50
	if val, ok := args["Age"]; ok {
		age = val.(int)
	}

	return fmt.Sprintf("Name: %s, Age: %d", name, age)
}

Output:

Name: default-name, Age: 50
Name: Harry Potter, Age: 50
Name: Lady Gaga, Age: 40

 

Summary

Again, Golang does not support optional parameters (can not set default values for parameters). But there will always be use cases for optional arguments, thus developers must devise their own workarounds. Hope that the examples above give you an idea of how to deploy your own solution.

 

References

https://go.dev/tour/basics/12

 

Views: 291

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel