2

Trying to import a file go file but unable to do so.

I have one main file:

    main/
      main.go  
      go_single_file.go

package main

import (
"./go_single_file"
)

func main() {

}

and go_single_file:

package go_single_file

func hello() bool{
return true
}

when i try to import go_single_file in my main file i get some sort of import error.

I am doing something wrong but not sure what.

If i make a separate package and import it then it works but not if it's in same folder.

Can anyone tell how can i import a go file from same folder.

1
  • 4
    You don't import files in Go. Files in the same directory are part of the same package. See go.dev/doc/code#Organization Commented Mar 2, 2022 at 20:43

1 Answer 1

6

In Golang files are organized into subdirectories called packages which enables code reusability.

The naming convention for Go package is to use the name of the directory where we are putting our Go source files. Within a single folder, the package name will be same for the all source files which belong to that directory.

I would recommend you to use go modules and your folders structure should be like this.

.
├── main.go
├── go.mod
├── go_single_file
│   └── go_single_file.go

In your go_single_file.go you are not using exported names for the function hello. So your file inside the go_single_file/go_single_file.go would look like this.

package go_single_file

func Hello() bool{
    return true
}

Your main file would like this

package main

import (
    "module_name/go_single_file"
)

func main() {
   _ = go_single_file.Hello()

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.