Posts

Showing posts from November, 2021

DO NOT use the return of append function to create new slice in Go

For Golang developers, it is very common to use append function to append new elements into slice. The common syntax is like below: var slice := make([]int, 0) slice = append(slice, 123) And for some requirements, you may want to create a new slice based on an existing slice. We know the below the code will work perfectly. slice := []int{1,2,3} newSlice := make([]int, 0) newSlice = append(newSlice, append(slice, 4)...) Below is complete example code to show the result: package main import ( "fmt" ) func main() { // here create the origin slice with cap 10 to make sure that // the slice is big enough to hold more data      slice := make([]int, 0, 10)      slice = append(slice, []int{1, 2, 3}...)      newSlice := make([]int, 0)      newSlice = append(newSlice, append(slice, 4)...)      fmt.Println(slice)      fmt.Println(newSlice)      fmt.Printf("The...

How to add optional arguments in Go function without impacting the existing function calls

Unlike C# you can put "Optional" keyword to add optional arguments in function, there is no direct way to create optional parameters in Go functions. And there is no method overloading in Go either. Even so, if you really need to add optional arguments to an existing function, maybe because this function is in a common library which is called by different software modules and you don't want to update all the modules for this new argument change, there is still a way to implement optional arguments thanks to variadic arguments in Go functions. Variadic arguments allow developer to put any number of trailing arguments as the input of functions. For example: package main import ( "fmt" ) func main() { fmt.Printf("1 + 2 = %d\n", add(1, 2)) fmt.Printf("1 + 2 + 3 + 4 + 5 = %d\n", add(1, 2, 3, 4, 5)) } func add(args ...int) int { sum := 0 for i:=0; i < len(args); i++ { sum += args[i] } return sum } The output is: 1 + 2 = 3 1 ...