Does it make sense to have two packages in the same directory?

前端 未结 4 540
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 09:43

I have a project that provides a library (exports some funcs) and also must provide a command-line interface (there must be an executable file).

Example of directory

4条回答
  •  天涯浪人
    2020-12-16 10:04

    Just move your packages inside a new folder within the same directory of main.go. Remember to import the new package from the reference of the $GOPATH.

    Example:

    user@user:~/p/go/test/so-multipack$ ls -R
    .:
    a  main.go
    
    ./a:
    a.go
    user@user:~/p/go/test/so-multipack$ cat main.go 
    package main
    
    import (
        "../so-multipack/a"
    )
    func main(){
        a.Hello()
    }
    user@user:~/p/go/test/so-multipack$ cat a/a.go 
    package a
    import (
        "fmt"
    )
    func Hello(){
        fmt.Println("hello from a")
    }
    user@user:~/p/go/test/so-multipack$ go run main.go 
    hello from a
    user@user:~/p/go/test/so-multipack$ go build 
    user@user:~/p/go/test/so-multipack$ ls
    a  main.go  so-multipack
    user@user:~/p/go/test/so-multipack$ 
    

    Useful link:

    go build vs go build file.go

提交回复
热议问题