Golang新手问题:如何在Visual Studio Code项目中导入GitHub仓库
Golang新手问题:如何在Visual Studio Code项目中导入GitHub仓库 大家好,
我刚开始学习Go语言,并想尝试使用一个GitHub项目来将表格内容打印到控制台。我已经安装了git,并使用以下命令导入了该模块:
git clone https://github.com/jedib0t/go-pretty.git
当我将文档示例中的代码复制下来并保存为main.go时,我在VSCode中得到了以下代码:
package main
import (
"os"
"github.com/jedib0t/go-pretty/table"
)
func main() {
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(table.Row{"#", "First Name", "Last Name", "Salary"})
t.AppendRows([]table.Row{
{1, "Arya", "Stark", 3000},
{20, "Jon", "Snow", 2000, "You know nothing, Jon Snow!"},
})
t.AppendRow([]interface{}{300, "Tyrion", "Lannister", 5000})
t.AppendFooter(table.Row{"", "", "Total", 10000})
t.Render()
}
当我尝试在终端中运行此代码:go run main.go
我遇到了以下错误:
cannot find package "github.com/jedib0t/go-pretty/table"
我觉得这应该是个小问题,但我完全卡住了。
非常感谢您能提供的任何建议。
谢谢
更多关于Golang新手问题:如何在Visual Studio Code项目中导入GitHub仓库的实战教程也可以访问 https://www.itying.com/category-94-b0.html
你是通过 go get 安装这个包的吗?
更多关于Golang新手问题:如何在Visual Studio Code项目中导入GitHub仓库的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
感谢您的回复,不,我没有这样做,抱歉。我以为需要使用克隆命令。
您有什么建议?
- 将代码复制到 main.go 文件中
- 在项目文件夹的终端中使用命令行:
go get "github.com/jedib0t/go-pretty/table"?
编辑:我让它工作了!!感谢您花时间帮助我这个新手,GreyShatter,并为我的愚蠢道歉!!
问题在于你没有正确初始化Go模块。git clone只是下载了源代码,但没有设置Go模块依赖管理。
在你的项目目录中,需要先初始化Go模块,然后添加依赖:
# 1. 初始化Go模块(如果还没有go.mod文件)
go mod init your-project-name
# 2. 添加依赖
go mod tidy
# 3. 运行程序
go run main.go
或者,如果你已经克隆了go-pretty仓库到本地,可以这样设置:
# 在项目根目录执行
go mod init example.com/yourproject
go mod edit -replace github.com/jedib0t/go-pretty=../go-pretty
go mod tidy
检查你的项目结构应该类似这样:
your-project/
├── go.mod
├── go.sum
└── main.go
运行go mod tidy会自动下载所有依赖并更新go.mod文件。如果还有问题,确保GOPATH和GOROOT环境变量设置正确,或者尝试:
# 清理模块缓存
go clean -modcache
# 重新下载依赖
go mod download

