Search code examples
gopackage

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

// file bar.go
package main

import "fmt"

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

File main.go

// file main.go
package main

func main() {
  Bar()
}

In main.go i want to use func Bar() from bar.go. But when I run go run main.go it results in:

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

What can be done do run the code without an error?


Solution

  • Update 26th July 2019 (for go >=1.11)

    go run .
    

    Will work on windows as well.

    Original answer (for non windows environments)

    The code actually works. The problem was that instead of running go run main.go I should run:

    go run *.go