First from wechat public number “Go programming time”, please do not reprint without authorization

For a list of tutorials in this series, please click on the Basic Go Tutorial

Go is a static language. When you write code, you have strict requirements for types. If the types do not match, you may fail to compile.

Therefore, when writing code, it is necessary to often use type conversion, these knowledge points, for a novice, can be said to be a small threshold, often to search engines to find the answer.

Today I’ve summarized four of the most common conversion methods encountered in daily development, so that you can feel free to cast.

The first is explicit type conversion

Use the corresponding type function to convert an object of type INT8 to int16

package main

import "fmt"

func main() {
	var a int8 = 5
	fmt.Printf("%T \n", a)
	// output: int8

	b := int16(a)
	fmt.Printf("%T \n", b)
	// output: int16
}

Copy the code

For another example, first convert string to []byte (equivalent to []uint8) using the []byte function, and finally convert []byte back to string using the String function

package main

import "fmt"

func main() {
	var s1 string = "golang"
	fmt.Printf("%T \n", s1)
	// output: string

	s2 := []byte(s1)
	fmt.Printf("%T \n", s2)
	// output: []uint8

	s3 := string(s2)
	fmt.Printf("%T \n", s3)
	// output: string
}

Copy the code

This method also applies to self-defined structures and interface types, but it can only be used to convert structure types to interface types, not interface types to structure types.

Let me give you an example here

package main import "fmt" type People interface { Speak() } type Student struct { name string } func (s Student) Speak()  { fmt.Println("hello, Golang ")} func demo2(s People) {s.peak ()} func demo1(s1 Student) {// Struct type to interface s2 := People(s1) demo2(s2)} func main() { s1 := Student{name: "wangbm"} demo1(s1) }Copy the code

Second: implicit type conversion

Implicit conversions, which are done by the compiler, are not noticed by the developer during daily development.

Implicit conversion is most common in the following two cases. It is very simple. I will just use a screenshot and annotate it.

Function call conversion

The function is converted when it returns

Third: type assertion

After learning the second method, we already know that the following code will definitely fail to compile.

package main

import "fmt"

type Student struct {
	name string
}

func (s Student) Speak() {
	fmt.Println("hello, golang")
}

func demo2(s Student) {
	s.Speak()
}

func demo1(s1 interface{}) {
	demo2(s1)
}

func main() {
	s1 := Student{name: "wangbm"}
	demo1(s1)
}

Copy the code

The answer, of course, is no, simply because s1 is implicitly converted to interface{} after demo1, and demo2 requires Student, so the types do not match.

The solution is also fairly simple, as long as the use of type assertion, can implement static type conversion.

In case you’re new to Type Assertion, here’s a quick overview.

Type assertions can be used to determine whether an object is of a type.

There are two cases:

In the first case, if the object is of type T (struct type), you can declare success by asserting that the object is of type T.

In the second case, if the object is of type I (interface type), the assertion that the object is of type T succeeds, and returns an object of type T statically, which is equivalent to a type conversion.

If the type assertion fails, panic will be thrown. Use it with caution. If you don’t want it to throw panic, you can use another assertion syntax. Assertions are not today’s topic, I won’t expand on it here. For more details, please check out my previous article, which was very clear.

s, ok := x.(T)

Copy the code

It is also important to note that type assertions cannot be used to convert two generic types to each other. Type assertions can only be used to convert an object statically of type interface{} to a specific type.

Fourth: reconstruct the object

In previous tutorials (detailed diagrams: Static typing vs. dynamic typing), I used diagrams to explain static typing and dynamic typing in detail in Go.

One of the most important points is the following way of defining variables

Package main import "FMT" func main() {age := (int)(25) // equivalent to age := 25 fmt.Printf("type: %T, data: %v ", age, age) // output: type: int, data: 25 }Copy the code

This knowledge point can also be applied to type conversion.

package main

import "fmt"

func main() {
	var a int8 = 5
	fmt.Printf("%T \n", a)
	// output: int8

	b := (int16)(a)
	fmt.Printf("%T \n", b)
	// output: int16
}


Copy the code

These are my four types of conversion methods. If you have more native conversion methods, please let me know in the background.