Import GO files in same folder

I have created 3 files in a single directory i.e. main.go, json.go,handler.go.
I am unable to import function in main.go from the other two. As far as I know, we don’t need to import files as long as the files are in the same directory.

I’d start here:

Go programs are organized into packages. A package is a collection of source files in the same directory that are compiled together. Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package.

If those files are in the same folder as main.go, they should be in the same package (main) and instead of json.respondWithJSON you would just use respondWithJSON (since they’re in the same package). If you want to make a different package, put your files in a subfolder (for example /json) but I would also caution against creating a package called json because that conflicts with the stdlib.

2 Likes

Yeah that worked. Thanks alot

In Golang, when working with files in the same folder, engineers can import them using the relative import path. The import statement allows Golang engineers to access and utilize the functionalities defined in other Go files within the same directory.

To import a Go file from the same folder, follow these steps:

  1. Ensure that the Go files are located in the same directory or folder.
  2. In the file where you want to import another Go file, add the import statement at the top of the file before any other code.
  3. Use the relative import path to specify the file you want to import. The relative import path begins with a dot (.) to indicate the current directory, followed by the file name without the .go extension.

Here’s an example to illustrate the process. Let’s assume we have two Go files, file1.go and file2.go, located in the same folder.

file1.go:

package main

import (
	"fmt"
)

func FunctionInFile1() {
	fmt.Println("This function is defined in file1.go")
}

file2.go:

package main

import (
	"fmt"
)

func FunctionInFile2() {
	fmt.Println("This function is defined in file2.go")
}

func main() {
	FunctionInFile1() // Call function from file1.go
	FunctionInFile2() // Call function from file2.go
}

In the above example, file2.go imports file1.go using the relative import path. Both files are in the same folder, so we use . (dot) to indicate the current directory.

By importing file1.go, we can access the FunctionInFile1() function defined in file1.go from file2.go.

To run the code, you can use the go run command followed by the file name you want to execute, in this case, file2.go:

go run file2.go

The output will be:

This function is defined in file1.go
This function is defined in file2.go

By importing Go files from the same folder, Golang engineers can effectively organize and reuse code within their projects, improving modularity and maintainability.

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