Using a function from the same package but from different file

I have a package main in which there are 2 files:

  • main.go
  • api.go

In file main.go in main function I use findPetByID function

...
r.HandleFunc("/pet/{petId}", findPetByID).Methods("GET")
...

And in api.go file I declared a function findPetByID.
Both files declared in main package and VSCode sees no problem with it because there is no warnings and IDE is able to see function signature from the main fuction i.e. findPetByID func(w http.ResponseWriter, r *http.Request).

But when I start it then the ide shows me

# command-line-arguments
.\main.go:133:31: undefined: findPetByID 

What is wrong with it?

2 Likes

When you split your main package into multiple files, you need to manually specify all of them when doing go build or go run.

I’d strongly suggest to not split your main package over multiple files, but instead properly split those things into smaller packages.

In general I do not like huge main packages.

3 Likes

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