Golang : Proper way to set function argument default value
In PHP, it is easy to specify the default values of a function arguments. All you need to do is just specify $argument_variable = default_value
in the function arguments such as :
function word_limiter($str, $limit = 100, $end_char = '…')
{
...
}
In Golang, it is not permissible to specify default values in a function arguments using the same method in PHP. Attempt to specify default values for the function arguments will cause the source code parser to throw out syntax error
.
This example code below demonstrate the simplest way to set default values in Golang by using the IF statement.
Here you go!
package main
import (
"fmt"
"strconv"
)
func failExample(s string, i int) string {
// wrong way to set default values
// will override input parameters/arguments !!!
s = "empty"
i = -1
return s + strconv.Itoa(i)
}
func okExample(s string, i int) string {
// set default values -- the proper way
if s == "" {
s = "empty"
}
if i == 0 {
i = -1
}
return s + strconv.Itoa(i)
}
func main() {
result := failExample("abc", 123)
fmt.Println("Fail example : ", result)
result1 := okExample("abc", 123)
fmt.Println("Ok example 1 : ", result1)
result2 := okExample("", 123)
fmt.Println("Ok example 2 : ", result2)
result3 := okExample("", 0)
fmt.Println("Ok example 3 : ", result3)
}
Output :
Fail example : empty-1
Ok example 1 : abc123
Ok example 2 : empty123
Ok example 3 : empty-1
References:
https://www.socketloop.com/tutorials/golang-return-multiple-values-from-function
See also : Golang : How to make function callback or pass value from function as parameter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.1k Android Studio : AlertDialog to get user attention example
+8.2k Linux/Unix : fatal: the Postfix mail system is already running
+4.4k Unix/Linux : How to pipe/save output of a command to file?
+19.6k Golang : Check if os.Stdin input data is piped or from terminal
+6k Unix/Linux : Use netstat to find out IP addresses served by your website server
+5.6k Golang : Compound interest over time example
+12k Golang : Arithmetic operation with numerical slices or arrays example
+8.8k Golang : How to get username from email address
+8.8k Golang : Create and shuffle deck of cards example
+29.7k Golang : How to verify uploaded file is image or allowed file types
+5.9k Golang : How to search a list of records or data structures
+10.1k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery