英文:
Is this casting in golang?
问题
paxPayment, ok = dataObject.(*entities.PassengerPayment)
这行代码是一个类型断言操作。括号的作用是将dataObject
转换为*entities.PassengerPayment
类型,并将结果赋值给paxPayment
变量。
类型断言用于判断一个接口类型的值是否实现了指定的接口或是指定的类型。在这个例子中,dataObject
被断言为*entities.PassengerPayment
类型,如果断言成功,paxPayment
将接收到转换后的值,并且ok
的值将为true
。如果断言失败,paxPayment
将接收到该类型的零值,并且ok
的值将为false
。
如果你还需要更多细节来回答这个问题,请提供更多相关的上下文信息。
英文:
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?
答案1
得分: 179
这是一个类型断言(Type assertion)。类型断言可以用于以下目的:
- 从接口类型(interface type)的值中获取具体类型(concrete type)的值
- 或者从初始接口类型获取不同接口类型的值(具有不同方法集的接口类型,实际上不是原始接口类型的子集,因为可以使用简单的类型转换来实现)
引用规范中的描述:
> 对于一个接口类型的表达式 x
和一个类型 T
,主表达式
>
> x.(T)
>
> 断言 x
不是 nil
,并且存储在 x
中的值是类型 T
。x.(T)
的表示法称为 类型断言。
>
> 更准确地说,如果 T
不是接口类型,x.(T)
断言 x
的动态类型与类型 T
相同。在这种情况下,T
必须 实现 x
的(接口)类型;否则,类型断言无效,因为 x
不可能存储类型为 T
的值。如果 T
是接口类型,x.(T)
断言 x
的动态类型实现了接口 T
。
更具体地说,你的示例是一种特殊形式,它还报告了类型断言是否成立。如果不成立,ok
将为 false
,如果断言成立,ok
将为 true
。
这种特殊形式不会像下面的形式那样引发 panic:
paxPayment = dataObject.(*entities.PassengerPayment)
如果 dataObject
不持有类型为 *entities.PassengerPayment
的值,上述形式将引发 panic。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论