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

问题描述 投票:-1回答:1

我想做这样的事情

type Struct1 {
    a string
}
type Struct 2{
    b int
}

if something{
    c := Struct1{a:''}
}else{
    c := Struct2{b:1}
}

somefunc(c)

我知道我不能在一个块内声明c然后在外面访问它。

我试过这样的事

type Struct1 {
    a string
}
type Struct 2{
    b int
}

c := Struct2{b:1}
if something{
    c := Struct1{a:''}
}

somefunc(c)

它给出了错误 - Cannot assign Struct1 to c(type Struct2)

我怎样才能实现这样的目标?

go
1个回答
0
投票

你可以使用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

© www.soinside.com 2019 - 2024. All rights reserved.