go - 在golang的If-else block 中为变量分配不同的结构

标签 go

我想做这样的事情

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

https://play.golang.org/p/Z1cT9qjFmfU

关于go - 在golang的If-else block 中为变量分配不同的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47921219/

相关文章:

go - 使用 http.Client 和 http.Transport 为请求设置 header

docker - Go:在声明性Jenkinsfile中找不到

go - 将 JSON 对象 "as is"存储到数据存储中

go - Go插件中没有符号

go - 在 Sublime Text 中保存时运行 goimports?

map - 在 golang 中分配给 map

go - 循环依赖和接口(interface)

go - 如何在不使用 time.Sleep 的情况下等待所有 goroutines 完成?

go - 如果自动完成在我的 vs code golang 项目中不起作用,我该怎么办?

go - 将映射传递给导入的 Golang 包中的函数时出错