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

使用Visual Studio Code调试Go代码

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

I recently wrote about My Top VSCode Tips and Tricks and among them was Debugging.

我最近写了有关My Top VSCode技巧和窍门的文章 ,其中包括Debugging。

In this article, I'll cover 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, here's a really short short list of the best resource to start your Go journey.

如果您没有编写Go语言的经验,并且想学习,那么这里是开始您的Go语言之旅的最佳资源的简短简短清单。

建立 ( Setup )

You need have the following requirements met.

您需要满足以下要求。

  1. You know a little about Go to write a simple 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 should 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, and you should click on that link to install the necessary Go packages for the plugin to work efficiently.

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

We finally need to install a debugger for Go, called Delve. It's an open source project. To do this, there are detailed installation instructions for specific platforms. I'm using a Mac, so it's as straight forward as.

最后,我们需要为Go安装一个名为Delve的调试器。 这是一个开源项目。 为此,有针对特定平台的详细安装说明 。 我使用的是Mac,因此非常简单。

brewinstall go-delve/delve/delve

例子 ( Examples )

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

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

  • A simple 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中调试测试

示例1:复仇者 (Example 1: Avengers)

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}]

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调试Go代码

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

A configuration file is create 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, we should 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. It should open the Debug View.

使用Visual Studio Code调试Go代码

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

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

使用Visual Studio Code调试Go代码

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

Once the debugger should have moved to line 40.

使用Visual Studio Code调试Go代码

一旦调试器移至第40行。

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 Start is Alive

使用Visual Studio Code调试Go代码

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

Pretty awesome right.

非常棒的权利。

条件断点 (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 an expression we want evaluates to true. e.g 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

使用Visual Studio Code调试Go代码

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

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

使用Visual Studio Code调试Go代码

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

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

使用Visual Studio Code调试Go代码

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

When however we 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, now the Debug View opens, and the execution stops at the breakpoint. We can see the json is not displayed in the Debug Console

使用Visual Studio Code调试Go代码

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

Sweet!

甜!

调试测试 (Debugging Tests)

Let's add a new function to our file, for simple addition arithmentic.

让我们向文件中添加一个新函数,以实现简单的加法运算。

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

We then 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

使用Visual Studio Code调试Go代码

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

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

Let's add a breakpoint on line 10 if res != c, and click on debug test.

使用Visual Studio Code调试Go代码

if res != c ,让我们在第10行添加一个断点,然后单击debug test。

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.

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

回顾 ( Recap )

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 used a simple example here 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 it's execution.

我们在这里使用了一个简单的示例来解释这些概念,但是可以随时将调试器添加到任何现有项目中,并进行尝试。 您最终将减少用于记录执行期间给定点代码的值/状态的fmt.Println语句。

Happy Coding.

编码愉快。

翻译自: https://scotch.io/tutorials/debugging-go-code-with-visual-studio-code