Break up go project into subfolders

前端 未结 6 891
傲寒
傲寒 2020-12-30 01:18

I want to break my project up to subfolders.

I want this code structure:

├── main.go
└── models
    └── user.go

Where main.go is:

6条回答
  •  天涯浪人
    2020-12-30 01:48

    Your import should be an absolute one:

    import "github.com/abonec/go_import_problem/models"
    

    If you don't want to export your project to an external referential, you can do a:

    import "go_import_problem/models"
    

    (That is: "the name of your project folder accessible by GOPATH/your package")

    See "How to use custom packages in golang?".

    And you would use:

    models.User
    

    As mentioned in Effective Go:

    The importer of a package will use the name to refer to its contents, so exported names in the package can use that fact to avoid stutter.
    (Don't use the import . notation, which can simplify tests that must run outside the package they are testing, but should otherwise be avoided.)


    kostix adds in the comments:

    to reiterate, names of Go packages are always absolute (that is, there's no relative package names, neither with ./ nor with ../ or anything like that) but that names are "anchored" to one of the so-called workspaces listed in $GOPATH.

    When Go searches for a package, it looks through workspaces and tries to find a package in each of them, in order.
    The search is not recursive.
    And no, there's no requirement to encode URLs in package paths -- unless you want to make your package public.

提交回复
热议问题