欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用Visual Studio Code调试Go代码

程序员文章站 2022-07-16 16:37:28
...

This article will go over how to debug your Go code, so it goes without saying that a prerequisite for this article is that you understand the basics of writing Go.

本文将介绍如何调试Go代码,因此无需多说,本文的前提条件是您了解编写Go的基础知识。

If you do not have experience writing Go, and would like to learn, we recommend that you check out A Tour of Go to start your Go journey.

如果你没有经验写去,想学习,我们建议你看看围棋之旅 ,开始你的旅程去。

建立 (Setup)

You need have the following requirements met:

您需要满足以下要求:

  1. You know enough about Go to write a small program, or even a small http server.

    您对Go足够了解,可以编写一个小程序,甚至是一个小型http服务器。
  2. You have go installed in your machine and the environment variable $GOPATH is set. (It defaults to ~/go)

    您已经安装了计算机,并设置了环境变量$ GOPATH。 (默认为〜/ go)
  3. The path $GOPATH/bin is exposed to your PATH.

    $GOPATH/bin路径公开给您的PATH。

  4. You have Visual Studio Code installed.

    您已经安装了Visual Studio Code。
  5. You have the VSCode-Go plugin installed.

    您已经安装了VSCode-Go插件

Once you have this installed, when open any .go files in VSCode, you will be prompted on the bottom right of the status bar to Install Analysis Tools. Click on that link to install the necessary Go packages for the plugin to work efficiently.

一旦你安装了这个,当打开任何.go在VSCode文件,你会在状态栏的右下角提示Install Analysis Tools 。 单击该链接以安装必要的Go软件包,以使插件有效地工作。

We finally need to install Delve, an open-source debugger for Go. To do this, there are detailed installation instructions for specific platforms.

最后,我们需要安装Delve ,这是Go的开源调试器。 为此,有针对特定平台的详细安装说明

创建示例应用 (Creating a Sample App)

We’ll use two examples to debug our Go code.

我们将使用两个示例来调试Go代码。

  • A Go program that generates a JSON.

    一个生成JSON的Go程序。
  • We’ll write a function, write the test and see how we debug tests in VS Code

    我们将编写一个函数,编写测试并查看如何在VS Code中调试测试

Here’s the source code for the first example. Create a file main.go.

这是第一个示例的源代码。 创建一个文件main.go

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

// Avenger represents a single hero
type Avenger struct {
    RealName string `json:"real_name"`
    HeroName string `json:"hero_name"`
    Planet   string `json:"planet"`
    Alive    bool   `json:"alive"`
}

func (a *Avenger) isAlive() {
    a.Alive = true
}

func main() {
    avengers := []Avenger{
        {
            RealName: "Dr. Bruce Banner",
            HeroName: "Hulk",
            Planet:   "Midgard",
        },
        {
            RealName: "Tony Stark",
            HeroName: "Iron Man",
            Planet:   "Midgard",
        },
        {
            RealName: "Thor Odinson",
            HeroName: "Thor",
            Planet:   "Midgard",
        },
    }

    avengers[1].isAlive()

    jsonBytes, err := json.Marshal(avengers)
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Println(string(jsonBytes))
}

Here we are just defining a struct Avenger, and then creating an array of avengers, changing the status of one of them to alive, then converting the results to JSON, and finally printing it to STDOUT.

在这里,我们只是定义一个struct Avenger ,然后创建一个复仇者数组,将其中一个复仇者的状态更改为还活着,然后将结果转换为JSON,最后将其打印到STDOUT。

You can run the app with

您可以使用

go run main.go

[{"real_name":"Dr. Bruce Banner","hero_name":"Hulk","planet":"Midgard","alive":false},{"real_name":"Tony Stark","hero_name":"Iron Man","planet":"Midgard","alive":true},{"real_name":"Thor Odinson","hero_name":"Thor","planet":"Midgard","alive":false}]

使用断点进行调试 (Debugging with Breakpoints)

To get started with debugging, we need to create a configuration. Click on the Debug Icon on the left pane of Visual Studio Code. Next, click on the gear Icon to create a configuration.

要开始调试,我们需要创建一个配置。 单击Visual Studio Code左窗格上的“调试”图标。 接下来,单击齿轮图标以创建配置。

使用Visual Studio Code调试Go代码

A configuration file is created under .vscode/launch.json with the contents shown above. Change the configurations program to point to the main.go file. In this instance, since we only have a main.go file, we can change it to our workspace root:

.vscode/launch.json下创建一个配置文件,其内容如上所示。 更改配置程序以指向main.go文件。 在这种情况下,由于只有main.go文件,因此可以将其更改为工作区根目录:

"program": "${workspaceRoot}",

We’re set. Next we need to add a breakpoint, because that’s what debugging is all about.

出发了 接下来,我们需要添加一个断点,因为这就是调试的全部目的。

Let’s add a breakpoint on line 21 func main() by clicking to the left of the line number. There, you will see a red dot.

我们通过单击行号左侧的第21行func main()添加一个断点。 在那里,您将看到一个红点。

使用Visual Studio Code调试Go代码

Next, either press F5 or Click on the Launch button with a green play button on the Debug Section on the top left to open the Debug View.

接下来,按F5或单击左上角“调试”部分上带有绿色播放按钮的“启动”按钮,以打开“调试”视图。

使用Visual Studio Code调试Go代码

Click twice on the Step Over button on the Debug Toolbar.

在“调试工具栏”上的“ Step Over按钮上单击两次。

使用Visual Studio Code调试Go代码

The debugger will have moved to line 40.

调试器将移至第40行。

使用Visual Studio Code调试Go代码

The Debug Section on the left will give us the state of the current breakpoint position.

左侧的“调试”部分将为我们提供当前断点位置的状态。

使用Visual Studio Code调试Go代码

We can see the state/value of the variables, at that particular time in the Variables section.

我们可以在“变量”部分的特定时间查看变量的状态/值。

We can also see the the call stack, and at the moment the running function is the main function, and line 40.

我们还可以看到调用堆栈,当前运行函数是main函数,以及line 40

You can continue Stepping Over, you’ll see the value of avengers changes once we are past the line. Tony Stark is Alive

您可以继续Stepping Over ,一旦我们越过线,您将看到avengers的价值发生变化。 托尼·斯塔克还活着

使用Visual Studio Code调试Go代码

添加条件断点 (Adding Conditional Breakpoints)

VSCode breakpoints provide you with an option to edit breakpoints by giving them an expression, which most of the time is usually a boolean expression.

VSCode断点为您提供了一个选项,可以通过给它们一个表达式来编辑断点,大多数情况下,这些时间通常是布尔表达式。

For instance, on line 40, avengers[1].isAlive(), we could add a condition here that the breakpoint is only raised when the expression evaluates to true, as in avenger[1].Planet == "Earth"

例如,在第40行上, avengers[1].isAlive() ,我们可以在此处添加一个条件,即仅当表达式的计算结果为true时才产生断点,如avenger[1].Planet == "Earth"

To do this, right click on the breakpoint and select edit breakpoint.

为此,请在断点上单击鼠标右键,然后选择“编辑断点”。

使用Visual Studio Code调试Go代码

If you did not have a breakpoint, you can still right click, and you will be told to add a Conditional Breakpoint

如果没有断点,仍然可以右键单击,然后会提示您添加Conditional Breakpoint

使用Visual Studio Code调试Go代码

Let’s add the condition once we’ve selected any of the above. avenger[1].Planet == "Earth"

选择以上任意一项后,让我们添加条件。 avenger[1].Planet == "Earth"

使用Visual Studio Code调试Go代码

Now if you launch the debugger with F5, it will not stop at the breakpoint. The app will run fine, and you will see the results in the debug console.

现在,如果您使用F5启动调试器,它将不会在断点处停止。 该应用程序将正常运行,您将在调试控制台中看到结果。

使用Visual Studio Code调试Go代码

Next, edit the code to match what we expect. Change Tony Stark’s planet to Earth:

接下来,编辑代码以符合我们的期望。 将托尼·斯塔克的星球更改为Earth

// ....
{
    RealName: "Tony Stark",
    HeroName: "Iron Man",
    Planet:   "Earth",
},
//...

When we launch the debugger again with F5, the Debug View opens and the execution stops at the breakpoint. We can see the JSON is not displayed in the Debug Console

当我们再次使用F5启动调试器时,“调试视图”打开,执行在断点处停止。 我们可以看到JSON没有显示在调试控制台中

使用Visual Studio Code调试Go代码

执行进一步的调试测试 (Performing Further Debugging Tests)

Let’s add a new function to our file, enabling addition arithmetic:

让我们向文件中添加一个新函数,以启用附加算法:

func add(a, b int) int{
    return a+b
}

Create a test file main_test.go in the same directory, with the following contents:

在同一目录中创建测试文件main_test.go ,其内容如下:

package main

import "testing"

func Test_add(t *testing.T) {
    a, b, c := 1, 2, 3
    res := add(a, b)
    if res != c {
        t.Fail()
    }
}

The code just adds two numbers, and the test just calls the function.

该代码仅将两个数字相加,而测试仅调用该函数。

If you have VSCode-Go plugin installed however, you’ll see additional options at the top of the test function. run test and debug test

但是,如果您安装了VSCode-Go插件,您将在测试功能的顶部看到其他选项。 run testdebug test

使用Visual Studio Code调试Go代码

You can click on run test to run the test and see the results in the Output window.

您可以单击run test以运行测试,并在“输出”窗口中查看结果。

To debug the test however, maybe because we can’t figure out something, all we need to do is add a breakpoint, like we did before, and click on debug test.

但是,要调试测试,也许是因为我们无法弄清楚,我们需要做的就是像以前一样添加一个断点,然后单击debug test

Add a breakpoint on line 10: if res != c. Then, click on debug test.

在第10行上添加一个断点: if res != c 。 然后,点击debug test

使用Visual Studio Code调试Go代码

The Debug View is opened again and we can use the Debug Tool to step over and inspect the state on the variables section on the left.

调试视图再次打开,我们可以使用调试工具来检查并检查左侧变量部分的状态。

结论 (Conclusion)

Debugging is a critical part of developing software, and with tools such as Visual Studio Code, our lives can be made much easier.

调试是开发软件的关键部分,借助Visual Studio Code之类的工具,我们的生活可以变得更加轻松。

We’ve added the debugger to an example project to explain the concepts, but feel free to add the debugger to any of your existing projects and play around with it. You’ll end up reducing your fmt.Println statements used to log to see the value/state of code at a give point during its execution.

我们已经将调试器添加到示例项目中以解释概念,但是可以随时将调试器添加到任何现有项目中并进行操作。 您最终将减少用于记录执行期间给定时间点的代码的值/状态的fmt.Println语句。

翻译自: https://www.digitalocean.com/community/tutorials/debugging-go-code-with-visual-studio-code