Beginner Question About Structure Initialization

I’m learning Go (using 1.9.2 on Centos 7). Consider the following
trivial program, which works fine:

package main
import "fmt"
type symbol struct {
    name string
    fn func(int)
    options int
}
func main() {
symbols := [] symbol {
    {"jon",x, 4},
    }
    symbols[0].fn(13)
    fmt.Println("symbols:  ", symbols)
}
func x(arg int) {
    fmt.Println("x: arg = ", arg)
}

This does what I expect, which is to show how to
initialize a structure to contain various values.

I then tried to modify this program so that the structure
initialization is done outside any function, like so:

package main
import "fmt"
type symbol struct {
    name string
    fn func(int)
    options int
}
var symbols = [] symbol  {
    {"jon",x, 4,}
}
func main() {
    symbols[0].fn(13)
    fmt.Println("symbols:  ", symbols)
}
func x(arg int) {
    fmt.Println("x: arg = ", arg)
}

However, this doesn’t compile, saying
./bad.go:12:18: syntax error: unexpected newline, expecting comma or }

I don’t understand how to fix this. I have to admit that I don’t
know why one style would be preferred over the other, but I’d like to
understand how to correct the second case.

Cordially,
Jon Forrest

Read the error message, it tells you to have a comma at the end of line 12 is required, or you need to move the closing curly one line up.

in your first example the code is {"jon",x, 4},,but in your second example the code is {"jon",x, 4,}. you lose the comma。

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