Home > Back-end >  Go: Type Assertions - Is there an error in the spec?
Go: Type Assertions - Is there an error in the spec?

Time:11-21

Is there an error in the Go Spec Type Assertions?

A type assertion used in an assignment statement or initialization of the special form

v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool

yields an additional untyped boolean value.

What is the last example supposed to be and mean? var v, ok interface{} = x.(T) ?

I get an error in Go 1.19 syntax error: unexpected interface, expecting := or = or comma

CodePudding user response:

All of those lines are attempting the same operation: a typecast of x to type T. The value, ok, determines whether or not the cast was successful. In the last example you provided, the only difference is that instead of Go determining the type for v and ok, you've provided a type of interface{} for both. Declaring v and ok as interface{} doesn't change the values they contain. It would allow you to send them to functions or add them to collections that expect a type of interface{}, at which point they'd have to be cast again.

  • Related