写自定义包的源文件
注意路径!注意路径!注意路径!重要的事情说三遍!
这个文件夹及其源代码一定要放在GOPATH/GOROOT路径下,在调包时才能import到该文件!
在正确的路径下新建pack1文件夹,在文件夹中新建pack1.go,代码如下:
package pack1
type StructX struct {
A int
B float64
C string
}
调用自定义包
在main.go中代码如下:
package main
import (
"fmt"
"./pack1"
)
func main() {
struct1 := new(pack1.StructX)
struct1.A = 10
struct1.B = 16.0
struct1.C = "Mr_zwX"
fmt.Printf("A = %d\n", struct1.A)
fmt.Printf("B = %f\n", struct1.B)
fmt.Printf("C = %s\n", struct1.C)
}
/* A = 10
B = 16.000000
C = Mr_zwX */
可见性
由于可见性规则,在struct的body中不能用小写字母开头,如果我们把ABC换成abc,变量未定义!
# command-line-arguments
.\main.go:9:12: struct1.a undefined (cannot refer to unexported field or method a)
.\main.go:10:12: struct1.b undefined (cannot refer to unexported field or method b)
.\main.go:11:12: struct1.c undefined (cannot refer to unexported field or method c)
.\main.go:13:35: struct1.a undefined (cannot refer to unexported field or method a)
.\main.go:14:35: struct1.b undefined (cannot refer to unexported field or method b)
.\main.go:15:35: struct1.c undefined (cannot refer to unexported field or method c)
用vscode中dlv工具调试golang代码
安装dlv工具
可在cmd中命令行安装,把dlv调试器放在GOPATH的bin目录下,输入代码:
go install github.com/derekparker/delve/cmd/dlv
在调试窗口修改launch.json中的参数
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",//auto->debug
"program": "${fileDirname}",//${fileDirname}->代码所在文件夹路径
"env": {},
"args": []
}
]
然后就可以开始快乐地 debug了,变量值在左栏显示