类型转换和类型断言之间有什么区别? [英] What is the difference between type conversion and type assertion?

查看:51
本文介绍了类型转换和类型断言之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间的主要区别是什么?

What is the main differences between :

  1. v = t.(aType)//类型断言
  2. v = aType(t)//类型转换

我应该在哪里使用类型断言或类型转换?

Where should I use type assertion or type conversion ?

推荐答案

类型断言断言 t (接口类型)实际上是 aType t 将是 aType ;即包裹在 t 接口中的那个.例如.如果您知道您的 var reader io.Reader 实际上是一个 * bytes.Buffer ,则可以执行 var br * bytes.Buffer = reader.(* bytes.缓冲区).

A type assertion asserts that t (an interface type) actually is a aType and t will be an aType; namely the one wrapped in the t interface. E.g. if you know that your var reader io.Reader actually is a *bytes.Buffer you can do var br *bytes.Buffer = reader.(*bytes.Buffer).

类型转换将一种(非接口)类型转换为另一种类型,例如像 var id int64 = int64(x)那样的 var x uint8 到int64.

A type conversion converts one (non-interface) type to another, e.g. a var x uint8 to and int64 like var id int64 = int64(x).

经验法则:如果您必须将具体类型包装到接口中并希望返回具体类型,请使用类型断言(或类型切换).如果需要将一种具体类型转换为另一种具体类型,请使用类型转换.

Rule of thumb: If you have to wrap your concrete type into an interface and want your concrete type back, use a type assertion (or type switch). If you need to convert one concrete type to an other, use a type conversion.

这篇关于类型转换和类型断言之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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