在同一个目录中有两个包有意义吗? [英] Does it make sense to have two packages in the same directory?

查看:14
本文介绍了在同一个目录中有两个包有意义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,它提供了一个库(导出一些函数),还必须提供一个命令行界面(必须有一个可执行文件).

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).

目录结构示例:

whatever.io/
    myproject/
        main.go
        myproject.go

go 编译器需要 package mainfunc main 来开始执行.我的库需要 package myproject 我在上面放东西的地方.这是我在构建另一个尝试导入 myproject 的项目时 go 工具所说的:

The go compiler needs the package main and func main to start execution. My library needs the package myproject where I put stuff on it. This is what the go tool says when I am building another project that tries to import myproject:

main.go:5:2: found packages myproject (myproject.go) and main (main.go) in $GOPATH/src/whatever.io/myproject

所以我相信没有办法.

我应该将库或 CLI 移动到另一个包吗?

Should I move the library or the CLI to another package?

推荐答案

只需将你的包移动到 main.go 同一目录下的一个新文件夹中.记得从 $GOPATH 的引用中导入新包.

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.

例子:

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$ 

有用的链接:

go build vs go build file.go

这篇关于在同一个目录中有两个包有意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆