For example, I have a simple project called demo
demo
├── go.mod
├── main.go
└── sum.go
Here is the code, for go.mod
, you can run go mod init
under demo directory to generate automatically(but you can create in yourself to)
// main.go
package main
import "fmt"
func main() {
num3 := sum(1, 2)
fmt.Println(num3)
}
// sum.go
package main
func sum(num1 int, num2 int) int {
return num1 + num2
}
// go.mod
module demo
go 1.17
Now in main.go
file, right click mouse → Run Code, that means you will run main.go with Code Runner, but it will print an error
# command-line-arguments
demo/main.go:6:10: undefined: sum
The reason for this error is that Code Runner only runs the main.go
file, if we cd
to demo path in the Terminal and run go run .
, the code can run very well.
How can we solve this problem?