My struct wrote in separate file is undefined in main.go

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)
}

Error:

main.go:8:11: undefined: Season

1 Like

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.

2 Likes

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.

Just go install.

And, https://golang.org/doc/code.html

3 Likes

try go run main.go season.go

1 Like

go run *.go

this will work as well, it includes all .go files in same folder

4 Likes

But only when not in windows… Go does not do any globbing, it relies on the shell in this regard.

1 Like

Thanks. Both go install and go run *.go works under Linux. Should I click something to make the topic is SOLVED or close somehow ?

1 Like

Its fine @Veliko_Kosev

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