How can I “go run” a project with multiple files i

2019-01-10 08:17发布

I currently have a single file in my main package called main.go. How do I split the contents of main.go into multiple files without creating a separate package because the code isn't reusable.

I want a directory structure like this:

$ ls foo

main.go
bar.go

bar.go

package main

import "fmt"

func Bar() {
    fmt.Println("Bar")
}

Then in main.go

package main

func main() {
    Bar()
}

But go run main.go gives me:

# command-line-arguments
./main.go:4:2: undefined: Bar

标签: go
5条回答
劫难
2楼-- · 2019-01-10 08:54

As mentioned in "How to compile Go program consisting of multiple files?", go run expects a list of files, since it "compiles and runs the main package comprising the named Go source files".
So you certainly can split your main package in several files with go run.

That differs from go build/go install which expect package names (and not go filenames).
A simple go build would produce an executable named after the parent folder.

Note that, as illustrated by this thread, a go run *.go wouldn't work in a Windows CMD session, since the shell doesn't do wildcard expansion.

查看更多
疯言疯语
3楼-- · 2019-01-10 09:00

As mentioned, you can say go run *.go but for Windows you can just list the script files (since *.go won't work) - go run main.go other.go third.go

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-10 09:00

For Windows install Cygwin and use it instead of command prompt. "go run *.go" will work then.

查看更多
Juvenile、少年°
5楼-- · 2019-01-10 09:05

If you are trying to run multiple files on localhost using gorilla mux in go as per latest version(1.11). Try using any of the following 2 commands.

  1. go install && FolderName -port 8081 .

  2. go build && ./FolderName -port 8081.

Make sure that you are in the source folder ie go/src/FolderName before executing the command in the Terminal.

查看更多
虎瘦雄心在
6楼-- · 2019-01-10 09:07

The code above actually works. The problem was I needed to run

go run *.go

instead of

go run main.go
查看更多
登录 后发表回答