doucuoyan0426
2017-12-21 08:49 阅读 102
已采纳

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

I want to do something like this

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

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

somefunc(c)

I know I can't declare c inside of one block and then access it outside.

I tried something like this

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

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

somefunc(c)

It gives error- Cannot assign Struct1 to c(type Struct2)

How can I achieve something like this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dshdsh2016 dshdsh2016 2017-12-21 08:56

    You can, use an 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

    点赞 评论 复制链接分享

相关推荐