这是在 golang 中铸造吗? [英] 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?
推荐答案
这是一个类型断言.类型断言可用于:
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).
引用规范:
对于接口类型的表达式x
和类型T
,主表达式
For an expression
x
of interface type and a typeT
, the primary expression
x.(T)
断言 x
不是 nil
并且 x
中存储的值是 T
类型.符号 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.
更准确地说,如果 T
不是接口类型,x.(T)
断言 x
的动态类型是 T
类型相同.在这种情况下,T
必须实现<代码>x;否则类型断言无效,因为 x
不可能存储 T
类型的值.如果T
是接口类型,x.(T)
断言x
的动态类型实现了接口T
.
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
.
更具体地说,您的示例是它的一种特殊形式,它还报告类型断言是否成立.如果不是,ok
将是 false
,如果断言成立,ok
将是 true
.
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)
如果 dataObject
不持有 *entities.PassengerPayment
类型的值,将会发生恐慌.
Which if dataObject
does not hold a value of type *entities.PassengerPayment
will panic.
这篇关于这是在 golang 中铸造吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!