Return a struct

I am trying to get several titles and contents from another go file. In order to do this I want first to understand how to fetch the struct. But I do not get it yet.

This works as expected

https://play.golang.org/p/QBefoC6lZOl

type Head struct{ Title, Content string }

func main() {
	fmt.Println(Head{"Your title page,", "A classic lorem ipsum content"})
}

I cannot get this to work when moving this to another function

https://play.golang.org/p/yLtghhu6fSb

type Head struct{ Title, Content string }

func main() {
	fmt.Println(Title())
}

func Title() interface{} {
	Head{"Your title page", "A classic lorem ipsum content"}
	return
}

It work when returning a simple string

https://play.golang.org/p/ZscEqXEcTuu

func main() {
	fmt.Println(Title())
}

func Title() string {
	return ("test")
}

What am I doing wrong? I have not worked with structs before.

It’s should be clear from compile errors:

  1. ./prog.go:14:6: Head literal evaluated but not used
  2. ./prog.go:15:2: not enough arguments to return
    have ()
    want (interface {})

just return what you’ve created:

return Head{"Your title page", "A classic lorem ipsum content"}

and it would be better return struct type:

func Title() Head {
	return Head{"Your title page", "A classic lorem ipsum content"}
}

Thank you!

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