goland无法运行go程序,如何查看GoLand调试器是否在程序中运行?

In C# the executing program can detect if it's running in the debugger using:

System.Diagnostics.Debugger.IsAttached

Is there an equivalent in Go? I have some timeouts which I would like to be disabled while I am stepping through the code. Thanks!

I am using the GoLand debugger.

解决方案

As far as I know, there is no built-in way to do this in the manner you described. But you can do more or less the same using build tags to indicate that the delve debugger is running. You can pass build tags to dlv with the --build-flags argument. This is basically the same technique as I described in How can I check if the race detector is enabled at runtime?

isdelve/delve.go

// +build delve

package isdelve

const Enabled = true

isdelve/nodelve.go:

// +build !delve

package isdelve

const Enabled = false

a.go:

package main

import (

"isdelve"

"fmt"

)

func main() {

fmt.Println("delve", isdelve.Enabled)

}

In Goland, you can enable this under 'Run/Debug Configurations', by adding the following into 'Go tool arguments:'

-tags=delve

1fb5e9415bf988ad5f7295b3e5b61a6f.png

If you are outside of Goland, running go run a.go will report delve false, if you want to run dlv on its own, use

dlv debug --build-flags='-tags=delve' a.go; this will report delve true.

Alternatively, you can use delve's set command to manually set a variable after starting the debugger.

Golang进行程序调试,首先需要确保你的开发环境已经搭建好,包括安装Go语言运行时环境、编辑器(如Visual Studio Code、GoLand等)以及调试工具(如Delve)。 以下是一个简单的示例,展示如何编写一个Go程序,该程序输出字符串“我爱Go语言”: 1. 打开你的Go编辑器,创建一个新的Go文件,例如命名为`main.go`。 2. 在文件输入以下代码: ```go package main import "fmt" func main() { fmt.Println("我爱Go语言") } ``` 3. 保存文件后,你可以在编辑器直接运行这个程序,通常编辑器会提供一个运行按钮或者快捷键来执行程序。 4. 如果你想要使用调试工具进行调试,首先需要安装Delve调试器。可以通过以下命令安装Delve: ```bash go install github.com/go-delve/delve/cmd/dlv@latest ``` 5. 安装完成后,在命令行进入你的项目目录,运行以下命令启动调试: ```bash dlv debug ``` 6. Delve启动后,会在一个新的命令行界面等待你的调试命令。你可以在Delve界面设置断点、单步执行、查看变量等。 7. 输入`continue`命令开始运行程序,当程序执行到`fmt.Println("我爱Go语言")`这一行时,你可以查看到输出结果。 8. 使用Delve的`next`命令可以单步执行代码,`print 变量名`可以查看变量的值。 以上步骤展示了如何在Golang编译环境调试程序,并输出特定的字符串。通过实践这些步骤,你可以更深入地了解Golang程序运行机制和调试技巧。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值