Home  >  Article  >  Backend Development  >  How to Debug Go Code in Visual Studio Code with Delve?

How to Debug Go Code in Visual Studio Code with Delve?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 01:07:02259browse

How to Debug Go Code in Visual Studio Code with Delve?

Debugging Go Code in Visual Studio Code with Delve

Setting up Delve debugger in Visual Studio Code for Go development requires the following steps:

Prerequisites:

  • Install the latest Go version and configure GOROOT and GOPATH.
  • Add $GOPATH/bin to your OS PATH environment variable.
  • Set environment variable GO15VENDOREXPERIMENT=1.
  • Install dlv: Run go get github.com/derekparker/delve/cmd/dlv and ensure the dlv binary is generated in $GOPATH/bin.
  • Install Visual Studio Code and the Go extension.

Setup:

  1. Open a folder in Visual Studio Code (Ctrl Shift E).
  2. Open the launch.json file in the .vscode folder.
  3. Set a breakpoint by clicking on the line number in the editor (F9).
  4. Press F5 to start debugging.
  5. Use keyboard shortcuts to control the debugger:

    • F10: Step Over
    • F11: Step Into
    • Shift F11: Step Out
    • Shift F5: Stop Debugging
    • Ctrl Shift F5: Restart Debugging

Example Configuration:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "go",
            "request": "launch",
            "mode": "debug",
            "program": "${workspaceRoot}",
            "env": {},
            "args": []
        }
    ]
}

Sample Code:

package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
    i := 101
    fmt.Println(i)
}

Result:

Visual Studio Code will launch the debugger and show the debug pane. You can hover over variables to see their values and use breakpoints to step through the code.

The above is the detailed content of How to Debug Go Code in Visual Studio Code with Delve?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn