Function arguments

Arguments

The arguments are variables which are accessible inside the function.

If you have simple variables, the content is copied, so changing the value inside the function does not change the original value:

func main(){
    name := "Bob" // name in scope main is "Bob"
    say(name)
    // name in scope main is still "Bob"
}

func say(name string){
    name = "alice"
    // name in scope main is still "Bob"
    // name in scope say is still "alice"
}

This is also called “call by value”.

If you want to return data from the function say, you have to return a valued.

Calling with pointers as arguments

Calling the function with a pointer, changing the content also changes the original variable.

func main(){
    name := "Bob" // name in scope main is "Bob"
    say(&name)
    // name in scope main is still "Bob"
}

func say(name *string){
    *name = "alice"
    // name in scope main is "alice"
    // name in scope say is still "alice"
}

This is also called “call by reference”.

See this example:

package main

import "fmt"

func main(){

        name := "Bob"
        say(name)
        fmt.Println("Name is still: ", name)

        sayRef(&name)
        fmt.Println("Name is now: ", name)
}

func say(name string){
        fmt.Println("Inside say: ",name);
        name = "Alice"
        fmt.Println("Inside say: ",name);
}

func sayRef(name *string){
        fmt.Println("Inside sayRef: ",*name);
        *name = "Alice"
        fmt.Println("Inside sayRef: ",*name);
}

Run the programm with:

go run main.go and you get:

Inside say:  Bob
Inside say:  Alice
Name is still:  Bob
Inside sayRef:  Bob
Inside sayRef:  Alice
Name is now:  Alice

Multiple arguments

Are separated with ,:

func main(){
    say("Alice", true)
}

func say(name string, printit boolean){
    if printit {
        fmt.Println(name)
    }
}

any Number of arguments

With three dots like ... you define that the function can take any number of arguments of this type.

This is used often on the GO SDK. Here the declaration of the S3 CopyObject function:

func (c *Client) CopyObject(ctx context.Context, params *CopyObjectInput, optFns ...func(*Options)) (*CopyObjectOutput, error)

That includes zero as a number, so this function call is valid:

s3Client.CopyObject(context.Todo(), myCopyObjectInput)

Now that we called a function with 0…n arguments, let’s look at the return values in the next section.

See also

Source

See the full source on github.

Sources