Method working with invalid number of arguments

package main

import (
        "fmt"
)

type test struct {
        name string
}

func (a test) show(b test) {
        fmt.Println(b.name)
}

func main() {
        test.show(test{name: "mother"})
}

The above code gives an error, but the below code works, I don’t understand why ?

package main

import (
        "fmt"
)

type test struct {
        name string
}

func (a test) show(b test) {
        fmt.Println(b.name)
}

func main() {
        test.show(test{name: "mother"},test{name: "father"})
}

I don’t understand why it works when I give 2 arguments to show method when, in declaration I have only defined one type.

Also, why does “father” gets printed and not “mother” ?

1 Like

Your example defines a type called test and you’re calling functions right on that type instead of calling them on instances of that type. Let’s change the receiver of your show method to a pointer to make the code more ugly and to see where “weird” stuff is happening: https://play.golang.org/p/T91W05TpbeZ

Now, let’s change the code so you’re calling methods like methods instead of functions on the type: https://play.golang.org/p/MRq8Yh4djju

Now it should be clearer that there’s a “this” parameter and then the other arguments. Now that we see it this way, we probably want to refactor the show function to show the current test, not a test passed as a parameter: https://play.golang.org/p/UgzaldqVL46

Method invocation in Go is somewhat like static functions in C#: they’re “syntactic sugar”

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.