Mujibur
Mujibur

Reputation: 1017

Golang struct issues to point parent struct method

I have encountered a problem in Golang as bellow:

package main

import "fmt"

type Foo struct {
    name string
}
type Bar struct{
    Foo
    id string
}

func (f *Foo) SetName(name string) {
    f.name = name
}    
func (f *Foo) Name() string {
    return f.name
}
func main(){
    f := &Foo{}
    f.SetName("Set Foo name")
    fmt.Println("Get from Foo struct name: ", f.Name() )    
    bar := &Bar{
    Foo:Foo{name: "Set Foo name from Bar struct!"},
    id: "12345678",    
    }
    fmt.Println("Bar setName(): ", bar.SetName("New value set to Foo struct name") )
    fmt.Println("Bar getName(): ", bar.Name())
}

Results:

./struct-2.go:33: bar.Foo.SetName("New value set to Foo struct name") used as value

But if I comment out this line then I can get the bar.Name() method works.

// fmt.Println("Bar setName(): ", bar.SetName("New value set to Foo struct name") )

Why I got that error for bar.SetName() method? Thanks.

Upvotes: 0

Views: 794

Answers (1)

icza
icza

Reputation: 418377

Answering the question so it won't show up anymore in the "Unanswered questions list".


You may pass values to other functions as input parameters. fmt.Println() has a variadic parameter of type interface{}. This means it accepts values of any type, and in any number (no limit on the number of passed arguments).

(f *Foo) SetName() has no return value. If you call this method either on a *Foo or *Bar, it will not produce any return values so you can't pass its "return value" to Println().

fmt.Println(bar.Name()) is OK because Name() returns a value of type string.

Upvotes: 1

Related Questions