-1

I don't understand why this doesn't work for this type of structure.

package main

import (
        "fmt"
)

var myStruct struct {
        number float64
        word   string
        toggle bool
}

myStruct.number = 3.14
myStruct.word = "pie"
myStruct.toggle = true

func main() {
        //myStruct.number = 3.14
        //myStruct.word = "pie"
        //myStruct.toggle = true
        fmt.Println(myStruct.number)
        fmt.Println(myStruct.toggle)
        fmt.Println(myStruct.word)
}

If I try to change myStruct.number outside main, I get a compilation error syntax error: non-declaration statement outside function body, but it works fine inside the function. With variables or other types of data structures, it works fine to change values outside main scope, but not with struct.

The program is an example from Head first Go, and even if I searched at least three more books and google for more information, I haven't found something similar that would be better explained.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Alex_N
  • 19
  • 2
  • 2
    This syntax is just not allowed by the language spec. There is nothing to explain or know here. This is just not valid Go code. Assignments like `myStruct.toggle = true` are allowed only inside functions. The compiler less you exactly what is wrong: Outside of functions only declarations. – Volker Feb 18 '21 at 08:52

1 Answers1

2

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

package main

import (
    "fmt"
)

var myStruct = struct {
    number float64
    word   string
    toggle bool
}{
    number: 3.14,
    word:   "pie",
    toggle: true,
}

func main() {
    //myStruct.number = 3.14
    //myStruct.word = "pie"
    //myStruct.toggle = true
    fmt.Println(myStruct.number)
    fmt.Println(myStruct.toggle)
    fmt.Println(myStruct.word)
}
vearutop
  • 3,924
  • 24
  • 41