-1

I'm just starting to learn Go and I'm wondering how to best organize my project and import packages. I created a project at $GOPATH/src/my_project. It contains the file main.go and the folder foo containing the file bar.go.

  • $GOPATH/src/my_project
    • main.go
    • foo/
      • bar.go

My main.go looks as follows

package main

import (
    "./foo"
    "fmt"
)

func main() {
    fmt.Println("Main")
    foo.Baz()
}

Here is the foo.go

package foo

import "fmt"

func Baz() {
    fmt.Println("Baz")
}

It works the way I expect it to, but I wonder if this is really the right way to structure a project and import packages, because most tutorials only import packages from github and never from local.

Thanks for your answers..

Iterator
  • 81
  • 4
  • nothing wrong here. you can read more questions and their answers using the search bar https://stackoverflow.com/search?q=%5Bgo%5Dproject+structure –  Dec 04 '20 at 22:33
  • 1
    Ignore random tutorials, read "How to Write Go Code" and abandon GOPATH builds and use modules. – Volker Dec 04 '20 at 22:34

1 Answers1

0

Relative imports are possible in Go but they are not encouraged to be used.

Instead you always use the full path of the package. In your case that would be my_project/foo. This is is relative to the GOPATH/src folder.

However, since we have Go modules now which make things a tiny bit more complicated to start with but have a lot of advantages in the long run.

Just earlier today I gave a step by step guide on how to set up a new project with Go modules: After go install the import doesn't recognize the package

The module name in this guide is the basis for your project then and all paths in the module build on that path. Let me give an example:

Let's say you name your module github.com/yourName/myProject. Then you can import the subpackage foo with github.com/yourName/myProject/foo.

Note: The module path should be the same as the git URL, that way you can just get the module with go get. If you don't plan on ever uploading the project to github or another git URL, you should still choose a unique name. Starting with a domain you own is a good idea -- for uniqueness.

TehSphinX
  • 6,536
  • 1
  • 24
  • 34