Is this casting in golang?

64,479

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 type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

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.

Share:
64,479
Varun Patro
Author by

Varun Patro

GoLang Enthusiast

Updated on July 13, 2022

Comments

  • Varun Patro
    Varun Patro almost 2 years

    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?