Is this a golang casting?

paxPayment, ok = dataObject.(*entities.PassengerPayment)

What are parentheses used for? I am not sure what is going on in this assignment operation.

Do you need any details to answer this question?

+22
source share
1 answer

This is a type statement . A type statement can be used to:

  • get a value of a specific type from an interface type value
  • or to get a value of an interface type different from the original one (an interface with a different set of methods is practically not a subset of the original one, since this could simply be obtained with a simple type conversion ).

I quote from the specification:

For an expression x type interface and type T main expression

 x.(T) 

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

More precisely, if T not an interface type, x.(T) claims that the dynamic type x is identical to the type T In this case, T must implement the type (interface) x ; otherwise, a type statement is not valid because x can store a value of type T If T is an interface type, x.(T) claims that the dynamic type x implements the T interface

More precisely, your example is a special form that also tells you whether a type statement is valid. If not, ok will be false , and if the statement is complete, ok will be true .

This special form never panics, unlike the form:

 paxPayment = dataObject.(*entities.PassengerPayment) 

Which, if dataObject does not contain a value of type *entities.PassengerPayment dataObject will panic.

+34
source

All Articles