英文:
Generic variable for architecture-specific structs
问题
我有一段代码需要在 MIPS 和 x86 上运行。为了简化操作,我在 mylib_x86.go
和 mylib_mips.go
中实现了具有相同名称的函数,并且还使代码能够在这两个平台上构建和运行。以下是一些代码片段,展示了我的结构体布局。
为了进一步优化代码,我在 common.go
中为每个平台声明了单独的结构体。
// lib/common.go:
// MIPS 的结构体
type MipsData struct {
var1 string
var2 string
var3 string
}
// x86 的结构体
type X86Data struct {
var2 string
var3 string
}
我想通过在 main()
中查询 runtime.GOARCH
来声明与架构相关的结构体,但是变量 data
的作用域被限制在每个代码块中,从而导致编译错误,类似于 error: reference to undefined name 'data'
。
import "lib"
import "strings"
import "runtime"
func main() {
if strings.HasPrefix(runtime.GOPATH, "mips") {
data := common.MipsData{
var1: "Mips",
var2: "Something",
var3: "Else",
}
} else if strings.HasPrefix(runtime.GOPATH, "amd64") {
data := common.X86Data{
var2: "Something",
var3: "Else",
}
}
text, err := json.MarshalIndent(data, "", " ")
// 将 text 写入文件。
}
是否有可能在 main()
中将 data
定义为通用数据类型以解决编译错误?还有其他解决这个问题的高效方法吗?
谢谢。
英文:
I have code that needs to run on mips and x86. To make things easier, I implemented functions with the same names and in mylib_x86.go
and mylib_mips.go
and also got code to build and work on both platforms. Below are some code snippets to show the layout of my structs.
In an attempt to further optimize my code, I declared separate structs for each platform in common.go
// lib/common.go:
// Struct for mips
type MipsData struct {
var1 string
var2 string
var3 string
}
// Struct for x86
type X86Data struct {
var2 string
var3 string
}
I'd like to declare the relevant struct for an architecture by querying runtime.GOARCH
in main()
but the scope of the variable data
is restricted to each block, thereby causing a compiler error like this: error: reference to undefined name 'data'
import "lib"
import "strings"
import "runtime"
func main() {
if strings.HasPrefix(runtime.GOPATH, "mips") {
data := common.MipsData{
var1: "Mips",
var2: "Something",
var3: "Else",
}
} else if strings.HasPrefix(runtime.GOPATH, "amd64") {
data := common.X86Data{
var2: "Something",
var3: "Else",
}
}
text, err := json.MarshalIndent(data, "", " ")
// Write text to a file.
}
Is it possible to define data
as a generic data-type in main()
to overcome the compile error? Are there any other efficient ways of solving this problem?
thanks
答案1
得分: 2
如果你只是想将这些结构体传递给json.MarshalIndent
,简单的解决方案是在if语句之外声明变量如下:
var data interface{}
它可以存储任何结构体,并且是json.MarshalIndent
所期望的类型。如果你想执行更多操作,这些操作应该适用于任何结构体,请考虑定义一个由每个结构体实现的接口,并使用该接口。
英文:
If you simply want to pass these structs to json.MarshalIndent
, the simple solution is to declare the variable as follows outside the if statement:
var data interface{}
It will be able to store either struct, and is the type expected by json.MarshalIndent
. If you want to perform more operations that should work on either structure, consider defining an interface implemented by each struct, and using that instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论