Functions
Notes// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.
Signature#
The signature of a function is as following:
func functionName (parameters)(return values){
<LOGIC>
}Parameters#
To pass a single parameter:
func helloWorld(param1 string) {
fmt.Println(param1)
}Pass two parameters:
func helloWorld(param1 string, param2 string) {
fmt.Println(param1)
fmt.Println(param1)
}If the parameters are the same type they can be declared once:
func helloWorld(param1, param2 string) {
fmt.Println(param1)
fmt.Println(param1)
}Variadic parameters uses an ellipsis operator converts the parameters into a collection of strings. The following example demonstrates param1 being converted to a slice:
func helloWorld(param1 ...string) {
for _, n:= range param1 {
fmt.Println(n)
}
}However, the caller of this function can pass in a single parameter at a time separated by commas multiple.
Variadic parameters can only be used once in a function and must be the last parameter defined.
Values and pointers#
When passing values into a function it is a copy of the value, so any manipulation done inside a function stays inside that function until the function exits. The original variable is unchanged in the main code flow.
In contrast, we can define a pointer, in which the opposite is true. Manipulation of a value inside a function WILL effect the global value in the code.
For example:
fun main(){
param1, param2 := "foo", "bar"
fmt.Println(param1)
fmt.Println(param2)
myFunction(param1 string, param2 *string)
fmt.Println(param1)
fmt.Println(param2)
}
func myFunction(param1 string, param2 *string) {
param1 = "hello"
*param2 = "world"
}Only use pointers to share memory, else use standard values.
Return Values#
Return a single value:
func main() {
result := addNumbers(1, 2)
fmt.Println(result)
}
func addNumbers(num1, num2 int) int {
return num1 + num2
}Return multiple values:
func main() {
result, ok := divideNumbers(1, 2)
if ok {
fmt.Println(result)
}
}
fun divideNumbers(num1, num2 int) (int, bool) {
if num2 == 0 {
return 0, false
}
return num1 / num2, true
}Named return values (rarely used):
func main() {
result, ok := divideNumbers(1, 2)
if ok {
fmt.Println(result)
}
}
func divideNumbers(num1, num2 int) (result int, ok bool) {
if num2 == 0 {
return
}
result = num1 / num2
ok = true
return
}