0

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.

2
  • 8
    SetName does not return anything, and you're trying to pass this "nothing" to fmt.Println. Which is impossible. Commented Dec 15, 2014 at 2:52
  • Oh ok sorry. Thanks for noticing Commented Dec 16, 2014 at 2:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.