I am reading the GO OS docs here https://golang.org/pkg/os/
The docs give this code
file, err := os.Open("file.go") // For read access.
if err != nil {
log.Fatal(err)
}
and then this
data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
log.Fatal(err)
}
However when I use it in this example I get the non-declaration outside function body.
How should I be using the documentation code in this example?
package main
import (
"encoding/xml"
"fmt"
"log"
"os"
)
type doc struct {
Meeting meeting `xml:"meeting"`
}
type meeting struct {
Race race `xml:"race"`
}
type race struct {
ID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Distance int `xml:"distance,attr"`
Noms []nomination `xml:"nomination"`
}
type nomination struct {
Number int `xml:"number,attr"`
ID int `xml:"id,attr"`
Horse string `xml:"horse,attr"`
Weight int `xml:"weight,attr"`
Rating int `xml:"rating,attr"`
}
func main() {
d := doc{}
err := xml.Unmarshal(file, &d)
if err != nil {
log.Fatalf("Unable to unmarshal XML: %s
", err)
}
fmt.Printf("%#v
", d)
}
file, err := os.Open("file.go") // For read access.
if err != nil {
log.Fatal(err)
}
data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
log.Fatal(err)
}
The error you're getting tells you exactly what is wrong. Your code is outside a function body. Only declarations can be outside of function bodies. You'll need to move the code into main() or another function that main calls.