How to import local packages without gopath

后端 未结 8 1926
有刺的猬
有刺的猬 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:29

    Since the introduction of go.mod , I think both local and external package management becomes easier. Using go.mod, it is possible to have go project outside the GOPATH as well.

    Import local package:

    Create a folder demoproject and run following command to generate go.mod file

    go mod init demoproject

    I have a project structure like below inside the demoproject directory.

    ├── go.mod
    └── src
        ├── main.go
        └── model
            └── model.go
    

    For the demo purpose, insert the following code in the model.go file.

    package model
    
    type Employee struct {
        Id          int32
        FirstName   string
        LastName    string
        BadgeNumber int32
    }
    
    

    In main.go, I imported Employee model by referencing to "demoproject/src/model"

    package main
    
    import (
        "demoproject/src/model"
        "fmt"
    )
    
    func main() {
        fmt.Printf("Main Function")
    
        var employee = model.Employee{
            Id:          1,
            FirstName:   "First name",
            LastName:    "Last Name",
            BadgeNumber: 1000,
        }
        fmt.Printf(employee.FirstName)
    }
    

    Import external dependency:

    Just run go get command inside the project directory.

    For example:

    go get -u google.golang.org/grpc
    

    It should include module dependency in the go.mod file

    module demoproject
    
    go 1.13
    
    require (
        golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect
        golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 // indirect
        golang.org/x/text v0.3.2 // indirect
        google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150 // indirect
        google.golang.org/grpc v1.26.0 // indirect
    )
    

    https://blog.golang.org/using-go-modules

提交回复
热议问题