从Bazel 1.21版本开始,引入了新的工作区模式,需要对Go目标进行一些调整才能成功构建。以下是解决方法的代码示例:
go.mod
的文件,用于定义Go模块。$ cd my_project
$ go mod init example.com/my_project
WORKSPACE
文件中引入go_repository
规则,指定要使用的Go版本和导入的依赖包。load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "io_bazel_rules_go",
remote = "https://github.com/bazelbuild/rules_go.git",
tag = "0.26.0", # 替换为你需要的版本号
)
load("@io_bazel_rules_go//go:def.bzl", "go_rules_dependencies", "go_register_toolchains")
go_rules_dependencies()
go_register_toolchains()
BUILD.bazel
文件,定义Go目标的构建规则。load("@io_bazel_rules_go//go:def.bzl", "go_binary")
go_binary(
name = "my_binary",
srcs = ["main.go"],
importpath = "example.com/my_project",
visibility = ["//visibility:public"],
)
main.go
的Go源代码文件,用于定义二进制目标的入口点。package main
import "fmt"
func main() {
fmt.Println("Hello, Bazel!")
}
$ bazel build //:my_binary
这样,你就可以使用Bazel成功构建Go目标了。请根据你的项目需要进行相应的调整,并确保安装了适当的Go工具链和依赖包。