Problem initializing nested structs

112 views
Skip to first unread message

Jason Gu

unread,
Jun 21, 2018, 11:34:54 PM6/21/18
to golang-nuts
Hi,

I've having trouble trying to initialize a struct with an embedded struct:

package game

type Config struct {
Size struct{ w, h int }
Gravity float64
speed int
}

package main

func main() {
   config := game.Config{
Size: struct{ w, h int }{ w: 800, h: 600 }, // Error: Cannot use struct{ w, h int }{ w: 800, h: 600 } (type struct {...}) as type struct {...}
}
}

I understand I can make "Size" an exported type in package game and that would work.

I'd like to know why can't I use struct literal for initialization; is it because the struct in (Size struct{ w, h int }) is an unnamed type and unnamed types are never exported?

pierre...@gmail.com

unread,
Jun 22, 2018, 2:19:42 AM6/22/18
to golang-nuts
Hello,

The reason is that the fields of the anonymous struct are not exported.
The error message actually mentions it:
"cannot use struct { w int; h int } literal (type struct { w int; h int }) as type struct { game.w int; game.h int } in field value"

Exporting those makes the program compile.

HTH

Miguel Angel Rivera Notararigo

unread,
Jun 22, 2018, 2:32:09 AM6/22/18
to golang-nuts
This works for me, just export the struct fields.

$GOPATH/test/main.go:

package main


import (
 
"fmt"

 
"test/game"
)



func main
() {
  config
:= game.Config{

   
Size: struct{ W, H int }{W: 800, H: 600},
 
}
 
  fmt
.Println(config)
}

$GOPATH/test/game/game.go:

package game


type
Config struct {

 
Size    struct{ W, H int }
 
Gravity float64
 
speed   int
}


Jason Gu

unread,
Jun 22, 2018, 5:06:31 PM6/22/18
to golang-nuts
Thanks! exporting the fields worked :)
Reply all
Reply to author
Forward
0 new messages