-2

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
Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45

2 Answers2

1

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

Vorsprung
  • 32,923
  • 5
  • 39
  • 63
0

In the terminal, you should use

go run .

instead of

go run main.go
Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
Kinichi
  • 54
  • 1
  • 5