这是在golang投射吗? [英] Is this casting in golang?
问题描述
paxPayment,ok = dataObject。(* entities.PassengerPayment)
括号用于什么?我不确定这次任务中发生了什么。
你需要更多的细节来回答这个问题吗?
它只是一个类型断言。类型断言可以用于:
规范:
对于接口类型的表达式
x
和类型<$主要表达式
x。(T)
/ code>
断言
x
不是nil
,并且存储在x
中的值的类型是T
。符号x。(T)
被称为类型断言。
,如果
T
不是接口类型,x。(T)
断言动态类型x
与相同Ť。在这种情况下, T
必须实施 (接口)类型x
;否则类型断言是无效的,因为x
不可能存储T
类型的值。如果T
是一个接口类型,x。(T)
断言动态类型x
实现了接口T
。
更多特别是你的例子是它的一个特殊形式,它也报告类型断言是否成立。如果不是, ok
将会是 false
,如果断言成立, ok
将是 true
。
这个特殊形式永远不会像以下形式那样恐慌:
$ b $ pre $
paxPayment = dataObject。(* entities.PassengerPayment)
如果 dataObject
不包含 * entities.PassengerPayment
类型的值,恐慌。
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 simply 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 typeT
, the primary expressionx.(T)
asserts that
x
is notnil
and that the value stored inx
is of typeT
. The notationx.(T)
is called a type assertion.More precisely, if
T
is not an interface type,x.(T)
asserts that the dynamic type ofx
is identical to the typeT
. In this case,T
must implement the (interface) type ofx
; otherwise the type assertion is invalid since it is not possible forx
to store a value of typeT
. IfT
is an interface type,x.(T)
asserts that the dynamic type ofx
implements the interfaceT
.
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.
这篇关于这是在golang投射吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!