Unable to import func A() of package main, inside another package main func main. There are 2 package main

737 views Asked by At

At package level main I have 2 files hello.go and main.go.

|- hello.go
|- main.go

Both the files are in package main level but unlike other packages I am unable to import a func defined in the hello in the func main. Can there be only 1 file with package main?

// hello.go
package main

import "fmt"

func Hello() {
  fmt.Println("hello world")
}

// main.go
package main 

func main() {
  Hello()
}

Error

./main.go:4:2: undefined: Hello
2

There are 2 answers

0
Kinichi On BEST ANSWER

In the terminal, you should use

go run .

instead of

go run main.go
0
Vorsprung On

two ways to make this work ok

  1. go build . then execute the binary

  2. with go mod:

 go mod init main
 go mod tidy
 go run main

looks like build can resolve the module to the current directory. Otherwise, you have to tell go where the module is