dse323222 2014-08-29 00:39
浏览 140
已采纳

在Go程序中使用多个文件

I wish to learn how to logically split my code in a Go package into multiple files, and crucially, the syntax necessary to use that split/separate file in another file of the same package.

I have created a go project in this form

-test
    -bin
    -pkg
    -src
        -main
            main.go
            test.go

and attempted to run go build main and go build main.go test.go, but I have always got an error.

test.go contains only this code

package main
import "fmt"
func do(b string) {
    fmt.Println(b)
}

I want to be able to call do("x") in main.go. Right now all that is in main.go is

package main
func main() {
    test.do("x")
}

I do not know what to do to get this to work. Many answers seem to suggest moving test.go into a directory "test". I am hoping Go does not require me to make a directory for every piece of code I write, but maybe I would be "fighting the system". Many answers have pointed me to a website telling me to make the above directory structure, and to use go install to compile my binaries, but that does not work.

I just want to know how to use functions in package/x.go inside package/y.go, even if they are in the same package. There has to be a way to do this, otherwise I will have either a bunch of unnecessary packages or hard to understand monolithic files.

I know there are many similar questions, but in my searching I haven't been able to find an actual example of the code in two files in the same package that reference each other.

  • 写回答

2条回答 默认 最新

  • duanfang5849 2014-08-29 00:45
    关注

    test.go has to be in the same package if is in the same directory. the package is thus main for both of the files and being in the same package you can just call do("x") .

    Additionally you can build the entire package like this without specifying the single files.

    export GOPATH="<path to>/test"
    
    go build main
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题