Go Type Assertion: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 15: Line 15:
</syntaxhighlight>
</syntaxhighlight>


=Type Assertion=
=Type Switch=
=Type Switch=
A type switch is a new [[Go_Language#Type_Switch|control structure]] introduced by Go.
A type switch is a new [[Go_Language#Type_Switch|control structure]] introduced by Go.

Revision as of 23:26, 13 August 2024

External

Internal

Overview

An interface hides the differences between the types implementing it and emphasizes the commonality. However, there are times you may want to know what exact concrete type exists behind the interface. Type assertions can be used for type disambiguation.

A type assertion is an expression that probes whether an interface is of a certain concrete type, and if it is, returns a variable of that type (see here for the code used in the example).

var i SomeInterface = &SomeImplementation{"test"}

v, ok := i.(*SomeImplementation)

Type Switch

A type switch is a new control structure introduced by Go.

Type assertion with switch:

var i SomeInterface
i = TypeA{"A"}

switch v := i.(type) {
  case TypeA:
	fmt.Printf("TypeA: %v\n", v)
  case TypeB:
	fmt.Printf("TypeB: %v\n", v)
}