Is this casting in golang?
Olivia Zamora
paxPayment, ok = dataObject.(*entities.PassengerPayment)
What are the brackets used for? I'm not sure what is going on in this assignment operation.
Do you need any more details to answer this question?
01 Answer
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
xof interface type and a typeT, the primary expressionx.(T)asserts that
xis notniland that the value stored inxis of typeT. The notationx.(T)is called a type assertion.More precisely, if
Tis not an interface type,x.(T)asserts that the dynamic type ofxis identical to the typeT. In this case,Tmust implement the (interface) type ofx; otherwise the type assertion is invalid since it is not possible forxto store a value of typeT. IfTis an interface type,x.(T)asserts that the dynamic type ofximplements 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.