How to import local packages without gopath

后端 未结 8 1975
有刺的猬
有刺的猬 2020-12-07 07:58

I\'ve used GOPATH but for this current issue I\'m facing it does not help. I want to be able to create packages that are specific to a project:

         


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-07 08:07

    Create some files like this:

    addition/aaa.go
    bbb.go
    

    The folder name will be one of your Module's packages. The file names can be whatever you want. Here is example package file:

    package addition
    
    func Add(n, n2 int) int {
       return n + n2
    }
    

    and the Module file:

    package main
    import "arithmetic/addition"
    
    func main() {
       n := addition.Add(1, 2)
       println(n)
    }
    

    Now initialize and build your module:

    go mod init arithmetic
    go build
    

    https://golang.org/doc/code.html

提交回复
热议问题