-2

The struct of interest is shown below

type rect struct {
width, height float64
testArray []struct{
    id    string
  }
}

I am trying to initialize the struct as shown below

r := rect{
    width: 10,
    height: 10,
    testArray: []struct{
        id: "wwwww",
    }, 
    {
        id: "wwwww",
    },
}

However it throws me an error saying

syntax error: unexpected :, expecting type

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user12140050
  • 109
  • 1
  • 1
  • 7
  • 2
    Does this answer your question? [Initialize nested struct definition](https://stackoverflow.com/questions/26866879/initialize-nested-struct-definition) – Peter Mar 07 '21 at 17:33
  • 1
    You will have a much easier time if you just give your type a name. – Peter Mar 07 '21 at 17:33
  • Thanks @Peter that actually helped me get a better understanding of how structs works in Golang. I was trying to initialize the struct as I was trying to write tests for an API. However, I ended up using a json config file for populating the data after, as that seemed more optimum. Really appreciate the help. – user12140050 Mar 07 '21 at 18:41

2 Answers2

0

Here is a working example:

type test struct {
   id string
}

type rect struct {
   height float64
   width float64
   testArray []test
}

func main() {
   r := rect{
      height: 10,
      width: 10,
      testArray: []test{
         {id: "April"},
         {id: "March"},
      },
   }
}
Zombo
  • 1
  • 62
  • 391
  • 407
0

Ofcourse the better fix would be to explicitly declare struct{id string} but the initial implementation isn't too bad either.

On your declaration you have testArray []struct{id string} where struct { id string } is your inline type. So only thing you were missing was a an extra braces and re-declaration of the inline struct:

r := rect{
    width: 10,
    height: 10,
    testArray: []struct{ id string} { // re declare the inline struct type
      { id: "April" }, // provide values
      { id: "March" },
     },
}
Kanak Singhal
  • 3,074
  • 1
  • 19
  • 17