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.
您需要满足以下要求。
- You know a little about Go to write a simple program, or even a small http server. 您对Go编写一个简单的程序甚至一个小型的http服务器有所了解。
- You have go installed in your machine and the environment variable $GOPATH is set. (It defaults to ~/go) 您已经安装了计算机,并设置了环境变量$ GOPATH。 (默认为〜/ go)
- The path
$GOPATH/bin
is exposed to your PATH.$GOPATH/bin
路径公开给您的PATH。 - You have Visual Studio Code installed. 您已经安装了Visual Studio Code。
- 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 <