-1

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?

Willis
  • 599
  • 3
  • 25

1 Answers1

1

If we want to run the code with Code Runner, we should add some config that can lets the Code Runner cd into the target folder and then run go run ..

open vscode setting page, click view json button on the top right corner enter image description here

Add the following config to the json

"code-runner.executorMap": {
    "go": "cd $dir && go run .",
},
"code-runner.executorMapByGlob": {
    "$dir/*.go": "go"
},

Be aware that the settings json may already have "code-runner.executorMapByFileExtension", but this is not the same with "code-runner.executorMap", do not add "go": "cd $dir && go run .", to "code-runner.executorMapByFileExtension".

After adding the config, now you can run your go code with Code Runner, you don't need restart or reload vscode.

Willis
  • 599
  • 3
  • 25