dse323222
dse323222
2014-08-29 00:39

在Go程序中使用多个文件

  • import
  • package
已采纳

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 duanfang5849 7年前

    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
    
    点赞 评论 复制链接分享
  • douguanyun2169 douguanyun2169 7年前

    Just do, not test.do. (body must be at least 30 characters; damn my natural talent for brevity!)

    点赞 评论 复制链接分享