Reputation: 673
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.
Upvotes: 2
Views: 2354
Reputation: 2565
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()
}
Upvotes: 6