英文:
Can I define my own runtime paramet like GOOS or GOARCH in golang?
问题
由于某种原因,我想在构建时使用一个参数来定义。例如 GOLIB=A go build
或 GOLIB=B go build
,并且在代码中使用它,如下所示:
if runtime.GOLIB == "A" {
// 做一些事情
}
if runtime.GOLIB == "B" {
// 做一些事情
}
有没有办法实现这个?
修改:
实际的问题是,我有一个新的操作系统(假设称为 A),它类似于 Linux,但有一些不同的 I/O 操作。因此,我想定义自己的类,比如 fd_A.go
、syscall_A.go
(就像 fd_unix.go/fd_windows.go
和 syscall.unix.go/syscall.windows.go
),它们实现了诸如 Bind,Accept,Recvform,Connect
等方法。
而上述的方法,如 UDP,TCP,HTTP
,将在构建项目时使用我定义的方法,使用 go build -tags A
,而不带 -tags A
则使用原始方法。
英文:
For some reason I want to use a paramet which define when building. Such as GOLIB=A go build
or GOLIB=B go build
, and use it like:
if runtime.GOLIB == "A"{
//dosomething
}
if runtime.GOLIB == "B"{
//dosomething
}
Is there anyway to did it?
Modify:
The really problem is that I have a new OS (suppoose called A ) which is similar with linux but has some different I/O operation. So I want to define my own class like fd_A.go
,syscall_A.go
(just like fd_unix.go/fd_windows.go
and syscall.unix.go/syscall.windows.go
),which implement the method like Bind,Accept,Recvform,Connect
etc.
And the upper method such asUDP,TCP,HTTP
will use the method I define when build project use go build -tags A
, but using origin method without -tags A
.
答案1
得分: 1
有没有任何方法可以做到这一点?
没有,至少不是你认为的这种方式。(你不能修改包的运行时。)
你有两个选择:
- 使用构建标签和文件,根据使用的构建标签定义适当的值。
- 在链接过程中使用
-ldflags "-X 'your/package/path.VariableName=YourValueHere'
来注入一个值。
这听起来像是一个XY问题。
英文:
> Is there anyway to did it?
No, at least not how you think this stuff works. (You cannot modify package runtime.)
You have two options:
- Build Tags and files defining appropriate values based on the build tag used.
- Inject a value during linkage with
-ldflags "-X 'your/package/path.VariableName=YourValueHere'
This sound like an XY problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论