Home > Article > Backend Development > Let’s talk about knowledge related to Golang forced transfer
When using Golang for development, we often encounter situations where type conversion is required, which is called forced type conversion or forced conversion. Coercion can convert a variable from one type to another, which is very useful when processing data. This article will introduce the relevant knowledge of Golang forced transfer, including data type conversion, pointer conversion, interface conversion, etc.
Forced conversion of data types
In Golang, the forced conversion of data types requires the use of parentheses to include the variable, and then add the type name of the data type that needs to be converted in front. For example, to cast a string to an integer, the example is as follows:
str := "123" num, err := strconv.Atoi(str) if err == nil { fmt.Println(num) }
In this example, the strconv.Atoi
function converts the string to an integer and returns a ## A value of type #int. In addition to the
strconv.Atoi function, there are some other functions that can perform type conversion, such as
strconv.ParseBool,
strconv.ParseFloat,
strconv .ParseInt etc.
float64 type to the
int type, the example is as follows:
f := 1.2 i := int(f) // f 被强制转换为 int 类型 fmt.Println(i)Force conversion of pointerIn Golang, pointer variables are stored The memory address of a variable can be accessed or modified through a pointer. Pointer variables can also be forcibly transferred. To cast a pointer, you need to use parentheses to include the pointer variable, and then add the type name of the pointer type that needs to be converted in front. For example, to convert a pointer variable of type
*int to a pointer variable of type
*string, the sample code is as follows:
num := 123 ptr := &num //ptr 是一个 *int 类型的指针变量 str := (*string)(unsafe.Pointer(ptr)) // str 是一个 *string 类型的指针变量In this example, we can see
unsafe.Pointer is used to perform pointer type casting. Although using
unsafe.Pointer is very convenient, it is not recommended due to its unsafety. If you need to use
unsafe.Pointer for pointer casting, please pay attention to comply with Golang's specifications and rules.
interface{}.(type). For example, to force conversion of an interface variable
i to a string type, the sample code is as follows:
var i interface{} i = "hello, world" str := i.(string) // i 被强制转换为 string 类型 fmt.Println(str)It should be noted that when performing forced type conversion of the interface, if the conversion fails, the program
panic exception will be thrown directly. You can avoid this by using the form
_, ok := i.(Type).
The above is the detailed content of Let’s talk about knowledge related to Golang forced transfer. For more information, please follow other related articles on the PHP Chinese website!