Home > database >  Strange method output
Strange method output

Time:11-27

I am confused about the output from my simple program. I expect to get all four names in the output, but I cannot get the first name in the output. Please help me clear this, or some resource about that.

type Employees struct {
    Name string
}

func main() {
    chandran := Employees{Name: "Chandran"}
    darpan := Employees{Name: "Darpan"}
    ishaan := Employees{Name: "Ishaan"}
    manbir := Employees{Name: "Manbir"}

    Employees.structName(chandran, darpan, ishaan, manbir)
}

func (e Employees) structName(names ...Employees){
    fmt.Println(names)
}

Code in go Playground

CodePudding user response:

There are no "static" methods in Go. To call a method, you must have a value of the receiver type, and call the method on that value.

So you must call it like this:

var e Employees
e.structName(chandran, darpan, ishaan, manbir)

Or simply:

Employees{}.structName(chandran, darpan, ishaan, manbir)

Both these output (try it on the Go Playground):

[{Chandran} {Darpan} {Ishaan} {Manbir}]

Why does your version omit the first argument?

Because what you have is in fact a method expression, and you are calling that method expression.

Let's look at it in details:

Employees.structName

is a method expression, and it is a callable function. Its signature is the signature of the structName method, the parameter list prefixed with the receiver. So the type of Employees.structName is:

func(main.Employees, ...main.Employees)

You call this by passing 4 employees, first of which will be the receiver, and only the remaining 3 will be used as the names argument. So only the names starting from the second will be printed.

CodePudding user response:

According to the language specification:

https://go.dev/ref/spec#Method_expressions

The expression

Employees.structName(chandran, darpan, ishaan, manbir)

is equivalent to:

chandran.strucName(darpan,ishaan,manbir)

This is because the first argument to the function Employees.structName is interpreted as the receiver to the method.

If you do:

Employees{}.structName(chandran, darpan, ishaan, manbir)

it will print all four elements.

CodePudding user response:

I think you should name your Strut Employee instead of Employees. since it represents only one employee. If you want to have methods on a group(slice) of employees.

type Employee struct {
    Name string
}

type Employees struct {
    employees []Employee
} 

then define function on that group type Employees:

func (e *Employees) Add(names ...Employee) {
    e.employees = append(e.employees, names...)
}

func (e Employees) structName() {
    fmt.Println(e.employees)
}

I made a small demo with an Add and StructName function.

  • Related