在VS Code中导入GitHub库时遇到的Golang错误

在VS Code中导入GitHub库时遇到的Golang错误 我尝试通过在 VS Code 终端输入 go get githubcom/stretchr/testify/assert 来从 GitHub 导入一个外部库,但遇到了以下错误:

# cd C:\Users\Rishabh\go\src\src\githubcom\stretchr\testify; git pull --ff-only
From https://githubcom/stretchr/testify
15aff29…e72b029  master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.
git pull <remote> <branch>

如果您希望为此分支设置跟踪信息,可以执行以下操作:

git branch --set-upstream-to=origin/<branch> master

package githubcom/stretchr/testify/assert: exit status 1

我已经在环境变量中添加了 git,路径为:C:\Program Files\Git\bin\go 我的 GOPATH 是:C:\Users\Rishabh\go\src\githubcom\rishabh(这是我创建项目的文件夹)。

我应该如何修复这个问题?

附注:所有出现 githubcom 的地方实际上都是 github.com。(因为这里只允许发布 2 个链接)


更多关于在VS Code中导入GitHub库时遇到的Golang错误的实战教程也可以访问 https://www.itying.com/category-94-b0.html

5 回复

@gastonpalomeque 谢谢,这个方法有效!

更多关于在VS Code中导入GitHub库时遇到的Golang错误的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


deadlegend:

在 VS Code 终端中执行 go get githubcom/stretchr/testify/assert

试试

go get githubcom/stretchr/testify

现在,出现这个错误:

无法加载包:包 github.com/stretchr/testify: 在 C:\Users\Rishabh\go\src\src\github.com\stretchr\testify 中没有 Go 文件

C:\Users\Rishabh\go\src\src\github.com\stretchr\testify 应该是 C:\Users\Rishabh\go\src\github.com\stretchr\testify

检查您的环境变量中 $GOPATH 是否正确,或者尝试从 $GOPATH/github.com 中删除 stretchr 文件夹,然后重新执行

go get github.com/stretchr/testify

这个错误是由于Git仓库缺少上游分支跟踪信息导致的。go get命令在获取包时会尝试更新现有仓库,但你的本地仓库没有设置远程跟踪分支。

以下是解决方案:

方法1:直接使用正确的go get命令

go get github.com/stretchr/testify/assert

方法2:如果已经克隆了仓库,手动设置上游跟踪 首先进入问题目录:

cd C:\Users\Rishabh\go\src\github.com\stretchr\testify

然后设置上游分支:

git branch --set-upstream-to=origin/master master

或者使用更简洁的方式:

git branch -u origin/master master

方法3:删除现有仓库重新获取

# 删除有问题的仓库
rmdir /s C:\Users\Rishabh\go\src\github.com\stretchr\testify

# 重新获取
go get github.com/stretchr/testify/assert

方法4:使用Go模块(推荐) 在你的项目根目录初始化Go模块:

# 进入项目目录
cd C:\Users\Rishabh\go\src\github.com\rishabh

# 初始化模块
go mod init github.com/rishabh/projectname

# 获取依赖
go get github.com/stretchr/testify/assert

这会创建go.mod文件,Go会自动管理依赖。

检查你的环境配置问题:

  1. Git路径应该是C:\Program Files\Git\bin\(不是...\bin\go
  2. 确保Git在系统PATH中:
git --version
  1. 检查GOPATH配置:
go env GOPATH

正确的导入代码示例:

package main

import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func TestExample(t *testing.T) {
    assert.Equal(t, 123, 123, "they should be equal")
}

主要问题是Git仓库配置不完整,go get无法自动完成更新操作。使用Go模块可以避免这类GOPATH相关的问题。

回到顶部