I have 2 files in the same folder one is season.go where I wrote a struct and method to that struct and the other file is main.go where I want to use the struct and the method of the struct, but when I go run main.go it keeps saying that MyStruct is undefined.
season.go
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
)
// Season struct used for Unmarshling the JSON object.
type Season struct {
Name string `json:"name"`
Rounds []rounds `json:"rounds"`
}
// Fetches data from the API for a certain season, 2016-17 for example.
func (s *Season) FetchAPI(interval string) {
response, _ := http.Get("https://raw.githubusercontent.com/opendatajson/football.json/master/" + interval + "/en.1.json")
data, _ := ioutil.ReadAll(response.Body)
json.Unmarshal(data, &s)
}
main.go
package main
import (
"fmt"
)
func main() {
var test Season
test.FetchAPI("2016-17")
fmt.Println(test.Name)
}
Do not use go run - it is only for running small scripts and only parses exactly the file given. Instead use go install to build and install your binary in $GOPATH/bin. Without parameters to build the package in the current dir, or give it a package path. Do not give it file names.
In main.go file, at import statement import season.go with full path name. Before doing this be sure to place season.go in season named directory and main.go in main directory. This will solve package issue completely
What? No. These files are in the same package and should be in the same package. There is no need for an import, imports refer to packages not files, and not by full path name.