3

I want to do something like this

type Struct1 {
    str1 string
}
type Struct2{
    int1 int
}

if something {
    someVar := Struct1{str1:''}
} else {
    someVar := Struct2{int1:1}
}

somefunc(someVar)

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

I tried something like this

type Struct1 {
    str1 string
}
type Struct2{
    int1 int
}

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

somefunc(c)

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

How can I achieve something like this?

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Still, I would recommend to use custom interface (type CustomStructInterface{}) instead of an empty one
@BohdanKostko indeed. In sake of simplicity I use an empty interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.