How Go language uses type conversion and type assertion

1

Introduction

Go language is a strongly typed programming language. Some readers who use weakly typed programming languages will be more or less uncomfortable with the types of Go language when they first learn Go language.

Go language variable types include basic types and composite types. Type conversion and type assertion generally deal with basic types. Basic types include integers, floating point numbers, Boolean and strings.

The integer type is also called an integer type, which is divided into signed and unsigned, each containing different sizes, 8-bit, 16-bit, 32-bit and 64-bit. The type aliases of int32 and uint8 are respectively rune and byte.

Floating point types are divided into float32 and float64. In order to avoid precision loss, we generally choose to use float64. Float32 and float64 can be directly converted, and integer and floating point types can also be directly converted. You need to pay attention to the problem of precision loss.

There are only two values of the Boolean type, true and false, and the zero value is false. Note that it cannot be implicitly converted to 1 and 0 like weakly typed programming languages.

The string type is a sequence of bytes enclosed in double quotes that can contain arbitrary data. It should be noted that it cannot be changed, because multiple strings can share the same memory space.

In this article we introduce type conversion and type assertion in Go language.

2

Type conversion

When we develop projects, we may encounter some scenarios that require type conversion. For example, we use Go language to develop API interfaces.

When the client (caller) requests the API interface we developed using the Go language, although it will follow the parameter types we have negotiated in advance, as the project continues to iterate, the previously defined variable types may need to be modified.

Because the Go language is a strongly typed language and does not support implicit type conversion, we need to explicitly convert the type of the variable.

Go language type conversion method:

Force conversion

Integer types can be forced to convert between each other, the code is as follows:

func main(){
    var a int64
    a = 1
    fmt.Printf("%T\t%d\
", a, a)
    var b int8
    b = int8(a)
    fmt.Printf("%T\t%d\
", b, b)
}

Read the above code, we define variable a of type int64, use the format of (), and directly change variable a from int64 Variable b converted to int8.

You can also force conversion between floating point number types and between floating point numbers and integer types. The code is as follows:

func main(){
    var a float64
    a = 3.1415926
    fmt.Printf("%T\t%f\
", a, a)
    var b float32
    b = float32(a)
    fmt.Printf("%T\t%f\
", b, b)
    var c int64
    c = int64(b)
    fmt.Printf("%T\t%d\
", c, c)
}

Read the above code, we define variable a of type float64, use the format of (), and directly change variable a from float64 is converted to variable b of float32, and then variable b is converted from float32 to variable c of int64. Need to pay attention to the problem of loss of precision.

The Boolean type bool has only two values, namely true and false. It has no other types that can be cast, but you can use the standard Library or third-party library performs type conversion on Boolean types.

The string type is a set of byte sequences enclosed in double quotes, so you can force conversion between string and []byte. The code is as follows:

func main(){
    var a string
    a = "golang"
    fmt.Printf("%T\t%s\
", a, a)
    var b[]byte
    b = []byte(a)
    fmt.Printf("%T\t%d\
", b, b)
}

Read the above code, we define a variable a of type string, use the format of (), and directly change variable a from string is converted to variable b of []byte and vice versa.

Use standard library or third-party library

For types that cannot be coerced, you can use the standard library or third-party libraries, such as Boolean types. The code is as follows:

func main(){
    var a bool
    a = true
    fmt.Printf("%T\t%t\
", a, a)
    var b string
    b = strconv.FormatBool(a)
    fmt.Printf("%T\t%s\
", b, b)
}

Reading the above code, we define a variable a of type bool, using the format of () and using the standard library strconv method converts variable a from bool to variable b of string.

In addition to the standard library strconv, the standard library fmt also provides type conversion methods; there are also some third-party libraries, such as cast. Due to space limitations, I will not go into details here. Interested readers can read the relevant documents to learn more.

3

Type assertion

When we develop a project, we may want to define the parameter type as a universal type. For example, we use Go language to develop an Api interface.

We want to try our best to adapt the client (caller) to use different types when passing parameters, for example, when the caller uses a weakly typed programming language.

We can define the empty interface type interface{} of the variable type, and then use type assertions to get the actual type of the passed parameters and process it into the type we want as needed.

Sample code:

func main(){
    var id interface{}
    id = 1 //The value received by parameter id is an integer
    fmt.Printf("%T\t%v\
", id, id)
    // You need to use the string type variable id to assign the value to the string type variable uid
    var uid string
    value, ok := id.(string)
    if ok {
        uid = value
    }
    fmt.Printf("%T\t%v\
", uid, uid)
}

Reading the above code, we define the variable id of the interface{} empty interface type. As a receiving request parameter, we actually need to use string type data. We use type assertions to check whether the value of the variable id is String type, if it is a string type, it is assigned to the variable uid.

It should be noted that when we use type assertions, it is best to use the ok-idiom mode to avoid triggering panic.

In addition, there is also type assertion in the form of switch case, also called type selection. Multiple types can be processed, the code is as follows:

func main() {
    var id interface{}
    id = 1 //The value received by parameter id is an integer
    fmt.Printf("0-%T\t%v\
", id, id)
    // You need to use the string type variable id to assign the value to the string type variable uid
    var uid string
    switch val := id.(type) {
    case string:
     uid = val
     fmt.Printf("1-%T\t%v\
", uid, uid)
    case int:
     uid = strconv.Itoa(val)
     fmt.Printf("2-%T\t%v\
", uid, uid)
    default:
     fmt.Printf("3-%T\t%v\
", uid, uid)
    }
}

Reading the above code, we use the switch case method to assert the parameter id. If the value of the parameter is the type we need, it will be used directly. Otherwise, it will be used after type conversion.

Careful readers may find that the format of the type assertion in this method is different, and the data type in parentheses is changed to type.

It should be noted that when using switch case type assertion, even if default is omitted, it will not be considered as a type assertion that is not in ok-idiom mode. And trigger panic.

4

Summary

In this article, we introduce the type conversion and type assertion in Go language that confuse readers who have been using weakly typed programming languages before.

After reading this article, everyone can at least distinguish the difference between type conversion and type assertion, and understand their respective usage scenarios.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Go Skill Tree Home Page Overview 4401 people are learning the system