这是在golang投射吗? [英] Is this casting in golang?

查看:97
本文介绍了这是在golang投射吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



括号用于什么?我不确定这次任务中发生了什么。



你需要更多的细节来回答这个问题吗?

解决方案

它只是一个类型断言。类型断言可以用于:


  • 从值获取具体类型的值。接口类型

  • 或者获取不同的接口类型的值比最初的接口类型(具有不同方法集,实际上不是原始方法的子集,因为只需使用简单类型 conversion )。



规范:


对于接口类型的表达式 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 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.

这篇关于这是在golang投射吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆