Calling go functions defined in same package but different folders

Hello Team,
I have the below code structure & I’m trying to call a function defined under the same package (main) but in different folder (I’m not sure if this is valid). If its valid, then my understanding is that I should be able to use the function defined in another “folder1” in main.go without explicit import right…?

Code structure:
| ---- main.go
---- folder_1
| ---- random.go

Undeclared name

Hi @Manish, welcome to the forum.

No, this is not valid. All files that belong to the same package must reside in the same folder, according to the language reference:

A set of files sharing the same PackageName form the implementation of a package. An implementation may require that all source files for a package inhabit the same directory.

(Packages - The Go Programming Language, emphasis added by me.)

(Where “implementation” refers to an implementation of a Go toolchain.)

The point is that import paths map to directories. So if you add a directory to your project, it represents a new import path.

Thanks a lot @christophberger for jet speed response. I will rework my code.

1 Like

as @christophberger said, you basically have 2 packages: dummy/main, and folder_1/main. You are dealing with 2 packages, they just happen to be both called main.

Also note that in your repo (for example, you could import both main packages in a 3rd package and use the code in both of them, like this:
import “
import “

1 Like

hmm @telo_tade thanks for the response. The folder_1 is under dummy folder (i.e its the subdir), so I was wondering since dummy is the parent folder it should be able to use the functions in folder_1 without explicit import, but I’m unable to.

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