Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this casting in golang?

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?

like image 488
Varun Patro Avatar asked Jul 13 '15 09:07

Varun Patro


People also ask

How do I cast a string in Golang?

In order to convert string to integer type in Golang, you can use the following methods. You can use the strconv package's Atoi() function to convert the string into an integer value. Atoi stands for ASCII to integer. The Atoi() function returns two values: the result of the conversion, and the error (if any).

What is type assertion in Golang?

Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type.

What do you know about type casting?

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.


1 Answers

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.

like image 105
icza Avatar answered Oct 02 '22 20:10

icza