我想做这样的事情
type Struct1 {
str1 string
}
type Struct2{
int1 int
}
if something {
someVar := Struct1{str1:''}
} else {
someVar := Struct2{int1:1}
}
somefunc(someVar)
我知道我不能在一个 block 内声明 c 然后在外部访问它。
我试过这样的东西
type Struct1 {
str1 string
}
type Struct2{
int1 int
}
someVar := Struct2{b:1}
if something {
someVar := Struct1{a:''}
}
somefunc(c)
它给出了一个错误- Cannot assign Struct1 to c(type Struct2)
我怎样才能实现这样的目标?
最佳答案
您可以使用接口(interface){}
package main
import (
"fmt"
)
type Struct1 struct {
a string
}
type Struct2 struct {
b int
}
func main() {
var c interface{}
if true {
c = Struct1{a: ""}
} else {
c = Struct2{b: 1}
}
fmt.Printf("type %T", c)
}
// Print:
// type main.Struct1
关于go - 在golang的If-else block 中为变量分配不同的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47921219/