简体   繁体   中英

change struct type in Go

I have two struct types

type type1 struct {
a1,b1,c1 string
}
type type2 struct {
a2,b2 string
}

and want to change type of variable p if the condition is true. How I am supposed to do it in Go ? Below does not work. And I think the question 'Golang : Is conversion between different struct types possible?' does not address this case because I am getting error "cannot convert p .. cannot use type2 as type1 in assignment ...too many values in struct initializer"

var p type1

    if <condition> {
        p = type2(p)
        p = type2{"1","2"}
    } 

Not possible.

According to my lame understanding of go type system, p is type1 , period. How the compiler would know what type is p after the if condition? The best you can do is to assign the fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM