dongying7667
dongying7667
2018-12-21 05:54

在Go中导入自定义包

I checked out this answer and for some reason either I was unable to comprehend properly or it didn't work

Also, Before I start, I got that How we can do it with github but I want to try it without github

To start let's say I have a main.go file

package main

import (
    "fmt"
    "math"
    "subpack"
)

//You Import packages without using comma in Go, rather space or new line
//In VS Code, if you use aren't using the package and run then it will automatically removie it

func main() {
    fmt.Println("hello world")
    //We use math.Floor to round the nunmber
    fmt.Println(math.Floor(2.7))
    fmt.Println(math.Sqrt(16))
    fmt.Println(subpack.Reverse)
}

Notice subpack here, it is the custom package I made. The subpack exsist like this

enter image description here

And contains the following code

package subpack

//If we make this in the same root level of our main it will throw an error

func Reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

running our go is throwing following error

cannot find package "subpack" in any of:
        /usr/local/go/src/subpack (from $GOROOT)
        /Users/anilbhatia/go/src/subpack (from $GOPATH)

Question: Is it possible and if yes, How to use custom package without github and without making it in the GO main folder rather by simply referencing the folder containing our go file from the directory we are working.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doudi8519 doudi8519 3年前

    As the error shows, the compiler cannot find subpack from either

    /usr/local/go/src/subpack (from $GOROOT)

    where the standard library packages (such as fmt, strings) are, or

    /Users/anilbhatia/go/src/subpack (from $GOPATH)

    where user installed/defined packages are.

    To make the import work, you just need to include the relative path of the subpack package (relative to $GOPATH/src) in your main.go

    Suppose your main.go is in /Users/anilbhatia/go/src/parentpack, then its import should be

    import "parentpack/subpack"
    

    If I understand you correctly, you want the caller of subpack (say main.go) to be in an unrelated location of subpack. This actually works out of box. Your main.go could be located anywhere. When you compile it, the compiler sees the import path of parentpack/subpack, and goes to $GOPATH/src and $GOROOT/src to find it.

    For more information about the source code organization and some typical examples, you can run

     go help gopath
    

    in your shell.

    点赞 评论 复制链接分享
  • donglan8999 donglan8999 3年前

    The starting point is $GOPATH/src not your project's folder.
    So you should use

    import "myproject/subpack"
    

    instead of :

    import "subpack"
    
    点赞 评论 复制链接分享

为你推荐