Interface ERROR: need type assertion

Hey there. I got the following function;

func IfThenElse(condition bool, a interface{}, b interface{}) interface{} {
	if condition {
		return a
	}
	return b
}

And I’m trying to use it like;

Saida1 = IfThenElse((funcoes_gerais.CopyStr(StatusBits1, 5, 1) == "0"), "1", "0")

Why do I get “need type assertion” error?

[EDIT]
Searching a bit more on Google I found the solution and this was adding “.(TYPE)” at the end of the function call, in my situation “.(string)”;

Saida1 = IfThenElse((funcoes_gerais.CopyStr(StatusBits1, 5, 1) == "0"), "1", "0").(string)

But now my question is; why do I need that?

Tnx.

Because you are returning an interface, which could be anything, you need to do a type assertion so Go knows what type the value has. https://tour.golang.org/methods/15

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.