Is this casting in golang?
Solution 1:
It's a Type assertion. A type assertion can be used to:
- obtain a value of concrete type from a value of interface type
- or to obtain a value of a different interface type than the initial one (an interface with a different method set, practically not subset of the original one as that could simply be obtained using a simple type conversion).
Quoting from the spec:
For an expression
x
of interface type and a typeT
, the primary expressionx.(T)
asserts that
x
is notnil
and that the value stored inx
is of typeT
. The notationx.(T)
is called a type assertion.More precisely, if
T
is not an interface type,x.(T)
asserts that the dynamic type ofx
is identical to the typeT
. In this case,T
must implement the (interface) type ofx
; otherwise the type assertion is invalid since it is not possible forx
to store a value of typeT
. IfT
is an interface type,x.(T)
asserts that the dynamic type ofx
implements the interfaceT
.
More specifically your example is a special form of it which also reports whether the type assertion holds. If not, ok
will be false
, and if the assertion holds, ok
will be true
.
This special form never panics unlike the form of:
paxPayment = dataObject.(*entities.PassengerPayment)
Which if dataObject
does not hold a value of type *entities.PassengerPayment
will panic.