4

Golang | 类型转换

 1 year ago
source link: https://jiac3366.github.io/2021/12/20/Golang/Go%E7%A8%8B%E5%BA%8F%E5%AE%9E%E4%BD%93/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

+c编程手记

Guangzhou, China
  • “类型断言”表达式 value, ok := interface{}(container).([]string) ——理解为python的isinstance()还有额外转换赋值功能

    • interface{}(container) 把container变量的值转换为空接口值,因为类型断言表达式的语法形式是x.(T)。其中的x必须是接口类型的,例如:.([]string) 判断前者的类型是否为切片类型 []string,如果是true,那么被判断的值将会被自动转换为[]string类型的值,并赋给变量value,否则value将被赋予nil(即“空”)

    • 区分对比:类型转换表达式的语法形式是T(x)
      x可以是一个变量,也可以是一个代表值的字面量(比如1.23和struct{}),还可以是一个表达式

  • 一对不包裹任何东西的花括号,除了可以代表空的代码块之外,还可以用于表示不包含任何内容的数据结构(数据类型),如:struct{}、interface{}、[]string{}、map[int]string{},而类型字面量是用来表示数据类型本身的若干字符,如:interface、map[int]string、[]string

  • GO的一些陷阱:

    • 1、uint8和int16之间的转换??

      • int16类型的值-255的补码是1111111100000001。如果我们把该值转换为int8类型的值,那么 Go 语言会把在较高位置(或者说最左边位置)上的 8 位二进制数直接截掉,从而得到00000001。所以var srcInt = int16(-255)dstInt := int8(srcInt) ——dstInt的值就是1
    • 2、当把一个浮点数类型的值转换为整数类型值时,前者的小数部分会被全部截掉

    • 3、字符’�’是 Unicode 标准中定义的 Replacement Character,专用于替换那些未知的、不被认可的以及无法展示的字符,由于-1肯定无法代表一个有效的 Unicode代码点, string(-1)所以得到的总会是”�”

    • 别名类型和潜在类型

      • type MyString = string,别名类型主要是为了代码重构而存在的,byte是uint8的别名类型,而rune是int32的别名类型,没有其他区别

      • type MyString2 string,MyString2是一个全新的类型,潜在类型相同的不同类型的值之间是可以进行类型转换的

        string可以被称为MyString2的潜在类型,表示MyString2 在本质上是string

        • MyString2类型的值与string类型的值可以使用T(x)表达式进行互转

        • 但对于集合类的类型[]MyString2与[]string来说这样做却是不合法的,因为[]MyString2与[]string的潜在类型不同,分别是[]MyString2和[]string


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK