How can I “go run” a project with multiple files in the main package?

I have a single file in the main package called main.go. Because the code isn’t reusable I want to separate part of the code in a different file but in the same package.

How do I split the contents of main.go into multiple files without creating a separate package?

I want a directory structure like this:

ls foo

# output:
main.go
bar.go
  • File: bar.go
package main

import "fmt"

func Bar() {
  fmt.Println("Bar")
}
  • File: main.go
package main

func main() {
  Bar()
}

When I run go run main.go, it gives me:

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

7 Answers
7

Leave a Comment