Golang中的类型断言和类型转换

Type assertion and Type conversion both are different concepts.

类型断言和类型转换都是不同的概念。

GoLang is a static type language where any variable must have a data type so that compiler knows its type that whether data will be stored in integer, string, float, etc. format. But in some cases, we are unaware of data type in that case interface comes into picture.

GoLang是一种静态类型语言,其中任何变量都必须具有数据类型,以便编译器知道其类型,即数据是否将以整数,字符串,浮点数等格式存储。 但是在某些情况下,在这种情况下,我们无法意识到数据类型。

Interface defines behaviour of data and can be used to store data of any type.

接口定义了数据的行为,可用于存储任何类型的数据。

var i interface{}
var count int = 5
i = count
fmt.Println(i)
i = "Hello World!!"
fmt.Println(i)

Interface stores two things, data and its type. Below is the diagram representation of interface storage.

接口存储两件事,数据及其类型。 下面是接口存储的示意图。

类型断言 (Type Assertion)

In general term, Assertion means a statement that you strongly believe is true.

一般而言 ,断言表示您强烈认为是正确的陈述。

Type assertion means to get value present inside the interface. Here is the syntext for this.

类型断言意味着在接口内部获取值。 这是此的上下文。

val, ok := interface.(TYPE)

It gives following outputs:

它提供以下输出:

  • Boolean value to ensure that expression ran successfully or not.

    布尔值,确保表达式成功运行或不成功。
  • Interface underlying value

    接口基础价值

Example:

例:

val, ok := i.(int)// ok will be true and val will hold value 5

Tricky part is that you must know the underlying type of variable. If you pass some other data type then it goes in panic mode so, it is always suggested to get boolean value to check whether assertion is done correctly or not.

棘手的部分是您必须知道变量的基础类型。 如果传递其他数据类型,则它将进入紧急模式,因此始终建议获取布尔值以检查断言是否正确完成。

val := i.(int32)// panic: interface conversion: interface {} is int, not int32

The other thing that we have to consider is that interface must have some value, if it is nil then type assertion will always give error

我们必须考虑的另一件事是接口必须具有某些值,如果为nil,则类型断言将始终给出错误

var i interface{}
val := i.(int32)// panic: interface conversion: interface {} is nil, not int32

Sometimes developer might have confusion that whether interface have int, int32 or int64, in that case we can use switch case.

有时,开发人员可能会对接口是int,int32还是int64感到困惑,在这种情况下,我们可以使用switch大小写。

switch i.(TYPE)
case: int
fmt.Printf("This type belongs to integer")
break;
case: int32
fmt.Printf("This type belongs to integer 32 bits")
break;
case: int64
fmt.Printf("This type belongs to integer 64 bits")
break;

i.(TYPE) only works with switch case.

i。(TYPE)仅适用于开关盒。

Type assertion works only with interface.

类型断言仅适用于接口。

类型转换 (Type Conversion)

Like its name say, it’s a way to convert a variable from one data type to another data type. Just think in this way like you have two bags having 5 and 10 KG capacity and now you need to exchange all content of 5 KG bag to 10 KG bag and vice-versa. 5 kg bag items can easily fit in 10 KG bag but reverse is not possible and we may end up losing some items.

顾名思义,这是一种将变量从一种数据类型转换为另一种数据类型的方法。 试想一下,就像您有两个分别具有5和10 KG容量的袋子,现在您需要将所有5 KG袋子的内容交换为10 KG袋子,反之亦然。 5公斤袋装的物品很容易装入10公斤袋中,但不可能反向,因此我们最终可能会丢失一些物品。

In most of the programming language, conversion of big data type to small data type is done by compiler itself but for reverse we need to tell compiler to do that but in golang, developer needs to explicitly tell the compiler to change the variable type in both cases.

在大多数编程语言中,大数据类型到小数据类型的转换是由编译器本身完成的,但相反,我们需要告诉编译器这样做,但是在golang中,开发人员需要明确地告诉编译器在两种情况下都更改变量类型案件。

T(v)
// converts the value

Lets see an example

让我们来看一个例子

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

Now run this program and see the output

现在运行该程序并查看输出

package mainimport "fmt"func main() {
var i int16 = 223
var j int8
j = int8(i)
fmt.Printf("i = %d and j = %d", i, j)
}Output:i = 223 and j = -33

Confused? Were you really expecting this output, if no then for this you need to go deep and see binary representation as we know computer understands binary language only.

困惑? 您是否真的希望得到此输出,如果没有,那么您需要深入了解二进制表示形式,因为我们知道计算机只能理解二进制语言。

Convert 256 into binary form which is 0000000011011111

将256转换为二进制形式0000000011011111

Now we need to fit this number in 8 bit register only. To do that you need to remove 8 bits from left and binary which is left is 11011111 and if you convert this number to decimal you will get -33. Now the question is how?

现在我们只需要将此数字放入8位寄存器即可。 为此,您需要从左侧删除8位,左侧的二进制为11011111 ,如果将此数字转换为十进制,将得到-33 。 现在的问题是如何?

Most left bit of this binary is 1 which shows that it is a negative number and to find out it’s decimal form we have to find two complements because it’s a negative number.

该二进制数的最左位是1,表示它是一个负数,要找出它的十进制形式,我们必须找到两个补数,因为它是一个负数。

Binary number =>     11011111
First complement => 00100000
Second complement => 00100000 + 1 = 00100001 => 33

So, decimal of this binary 11011111 is -33

因此,此二进制文件11011111十进制为-33

If you are getting confused, let’s think in this way that we have to fit 223 number in 8 bit register and in 8 bit we have range of -128 to 127.

如果您感到困惑,让我们以这种方式考虑,我们必须在8位寄存器中容纳223个数字,而在8位寄存器中,我们应将范围从-128到127。

Now count from 0 to 127 and then start with -128 for 223 you will end up to -33.

现在从0到127进行计数,然后以-128开头为223,最后将达到-33。

Similarly, we can convert int into string. At the core level computer gets binary form and then convert it according to data type.

同样,我们可以将int转换为字符串。 在核心级别,计算机获取二进制格式,然后根据数据类型对其进行转换。

There is no type casting word in Golang, it’s always type conversion

Golang中没有类型转换词,它始终是类型转换

翻译自: https://medium.com/swlh/type-assertion-and-type-conversion-in-golang-11fd98f69a3f

你可能感兴趣的:(golang,go)