Go On those things between the type conversion

Try to answer these questions and answer

What is s [i] and the difference (for _, v range) of v is
var s string = "AB"
fmt.Println(reflect.TypeOf(s[0]))
for _, v := range s {
   fmt.Println(reflect.TypeOf(v))
}
a. what (), and a (b) the difference is?
var v interface{} = 1
var s uint8 = 1

temp1 := int(s)
temp2 := v.(int)

fmt.Println(temp1,temp2)

Go to understand the type of system

Go type

Go language is a statically compiled language, is a strongly typed language, the language Go classified into two types: named types (defined type) and an unnamed type (combined type) , for example I talk about

  1. Named types (defined type)
uint8(byte) uint16 uint32 uint64 int int8 int16 int32(rune) int64 bool string
float32 float64 complex64 complex128

Examples of the above type classified into three categories: numerical, strings, Boolean type, we use any type defines the type also referred to as a named type, as follows

//也是命名类型
type MyBool bool 
  1. Type (combination type) Unnamed
slice map chan function interface struct pointer

Examples of types of containers of the above type, function type, pointer type, type of structure, Channel Type, Interface Type

Type definitions and underlying type

Go type keyword allows to define a type
of each type are a Go underlying type, the type of the underlying type has the following rules

  1. Each type of underlying type a name of his own
  2. Each combination of type of their underlying type are
  3. In a statement type, type and original new declaration of the type of underlying type is shared

The following code, will be able to compile this code to succeed? why? First, the failure of this code is compiled, type i is MyInt, j is of type int, although their underlying type is int, but can not be assigned to each other, it means that the namespace is not the type of assignment of each other, even low limit to a higher limit assignment, such as int32 int64 is assigned to compile failure

type MyInt int
func CustomType() {
   var i MyInt = 2
   var j int = 1
   j = i
   i = j
   fmt.Println(i == j)
}

The following code would be printed and the type of underlying basic types of these two variables,

//输出MyInt int
fmt.Println(reflect.TypeOf(i), reflect.TypeOf(j))
//输出int int
fmt.Println(reflect.TypeOf(i).Kind(), reflect.TypeOf(j).Kind())

We look at a Demo, the following code will compile error, and if the int32 int64 into it? The answer is a compilation error, change int64 will compile error, while the only change i j and int32 and int64, will compile successfully. Because when m and n underlying type are identical.

type MyM struct {
   i int64
}
type MyN struct {
   j int32
}
func TestStruct() {
   n := MyN{j: 10}
   var m MyM
   m = MyM(n)
  fmt.Println(n,m)
}
How to track the moon source of a type of underlying type

The following code, talk about what these types of underlying type is?

type MyInt int
type I MyInt
type Ints []int
type MyInts []MyInt
type M map[string]string
type CustomM M

MyInt type int underlying
the underlying type I int
Ints underlying type [] int
underlying type is MyInts slice
underlying class M is map
CustomM map of the underlying class is

Until the law is a built-in type (Go built-in type) or find an unnamed type (combined type) end, this type is the current type of underlying type

How to get a type of underlying type by code? Following code retrieves

reflect.TypeOf(variable).Kind()
Type alias

What is the type alias for it? There are two types of aliases Go byte, corresponding to the true type is uint8, rune, corresponding to a linear type int32, we can both source code is defined as follows

// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is
// used, by convention, to distinguish byte values from 8-bit unsigned
// integer values.
type byte = uint8

// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values.
type rune = int32

Can solve the first problem can be the beginning, s [index] is made from this string into a byte after byte, and refers to a range of characters each cycle of the string s (range will implicit unicode decoding), but the distinction between the characters and kanji letters, a letter one byte, not of a character, see the following code, you can get the underlying type of byte and rune

var r rune = 'c'
var b byte = 1
fmt.Println(reflect.TypeOf(r).Kind()) //int32
fmt.Println(reflect.TypeOf(b).Kind()) //uint8

How to define a type alias for it? Actually very simple, know how to define a type, then define a very simple type aliases, refer to the above byte and rune, as we have an alias (as defined int64 from Go1.9 began to support ), type alias may be declared function in vivo

//相比定义一个类型多了一个=号
type alaisInt64 = int64
Type conversion and assertions

Type conversion is used to convert between the different types, but the type of mutually compatible manner, if not compatible with each other can not be converted, compilation error, writing is usually a (b), to be converted into a b

Type assertion is performed between the interface, but also the nature of the type of conversion, is written a. (B), the meaning is to be converted into a b

The following code, doing something wrong and correct demonstration


//这个转换时类型不同,也不兼容,所以编译报错
s := "ab"
i := int(s)

//这个转换类型不同,但兼容,所以OK
var j int8 = 1
m := int(j)

//这个转换是失败的,系统会检测到类型不匹配,直接panic
var k interface{} = "s"
l := k.(int)
//但我们可以通过一个参数来判断,只有f为true时,才会转换成功
l,f := k.(int)
//这个转换是成功的
p,f := k.(string)

Practice type conversion, engage in active practice in order to understand

Conversion between numeric types

The high from the low rpm without any problems, from the time the high turn low (lose precision), int64 turn int8, this conversion process is as follows:
the binary 128: ......... 00000000_ 1 0000000
because it is transferred from int64 int8, it is taken after eight 128: 1 0000000
At this time most significant bit is 1, indicates that this is a negative number, the result is this case is: -128

//这个转换没有任何问题,都OK
var i int8 = 123
var j int16 = int16(i)
//这个转换会丢失精度,从高位转低位
var m int64 = 128
var n int8 = int8(m) //n的结果是-128,因为int8能表达的最大值是127,最小值是-128,
String, bytes, numbers, characters, each conversion
var s1,s2 string = "AbcD","1234"
//转字节
bs1 := []byte(s1); bs2 := []byte(s2)

//字节数组转字符串
s11 := string(bs1); s22 := string(bs2)
//单个字节转字符串
ss := string(bs1[0])
fmt.Println(s11, s22, ss)

//s2转数字 ,err 表示是否能转换成功,比如s1就会转换失败
i, err := strconv.Atoi(s2)
//数字转字符串
s := strconv.Itoa(i)

//字符串转字符数组
runes := []rune(s1)

//字符数组转字符串
ss1 := string(runes)
//单个字符转字符串
ss2 := strconv.QuoteRune(runes[0])

//字符转字节
bss := make([]byte, 0)
bss = strconv.AppendQuoteRune(bss, runes[0])
fmt.Println(err, s, ss1, ss2, runes[0], bss, string(bss))
//除开rune和byte底层的类型的区别,在使用上,
//rune能处理一切的字符,而byte仅仅局限在ascii

//整形转字节
x := int32(68)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
//字节转整形
var y int32
binary.Read(bytesBuffer, binary.BigEndian, &y)
Interface to a particular type of conversion
//由接口类型转换为具体的类型
var i interface{} = 1
t, f := i.(int)
if f { //转换成功
   fmt.Println(t)
} else {//转换失败
   fmt.Println(reflect.TypeOf(i).Kind(), reflect.TypeOf(i))
}

Welcome attention to public numbers, read more exciting articles

Guess you like

Origin www.cnblogs.com/sy270321/p/12171001.html