Table of Contents
What is an assertion?
Introduction to type assertion
Type Switch
Home Backend Development Golang What is type assertion in go language?

What is type assertion in go language?

Jan 12, 2023 am 10:57 AM
golang go language type assertion

In the Go language, type assertion is an operation used on interface values. It is used to check whether the value held by the interface type variable implements the expected interface or specific type. The syntax is "value, ok := x.(T)". What can be done through type assertions: 1. Check whether i is nil; 2. Check whether the value stored in i is of a certain type.

What is type assertion in go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

What is an assertion?

Assertion is a programming term expressed as some Boolean expression. When writing code, we always make some assumptions, and assertions are used to capture these assumptions in the code. To simply understand assertion, it means judgment. So in Go, we can understand type assertions as type judgments.

Introduction to type assertion

Type assertion (Type Assertion) is an operation used on interface values ​​to check whether the value held by the interface type variable is implemented The desired interface or specific type.

The syntax format of type assertions in Go language is as follows:

value, ok := x.(T)
Copy after login

Among them, x represents the type of an interface, and T represents a specific type (can also be an interface type).

This assertion expression will return the value of x (that is, value) and a Boolean value (that is, ok). You can judge whether x is of type T based on the Boolean value:

  • If T is a specific type, the type assertion will check whether the dynamic type of x is equal to the specific type T. If the check succeeds, the type assertion returns a dynamic value of x whose type is T.

  • If T is an interface type, type assertion checks whether the dynamic type of x satisfies T. If the check is successful, the dynamic value of x will not be extracted and the return value is an interface value of type T.

  • No matter what type T is, if x is a nil interface value, the type assertion will fail.

There are two main forms of type assertions in Go

  • Variable.(type). For example: i.(int)

  • variable, bool = variable.(type). For example: num,ok = i.(int). ok means to determine whether the type is successful.

Usage of type assertion

You can do the following things through type assertion

  • Check if i is nil

  • Check if i the stored value is of a certain type

There are two specific ways to use it:

The first one:

t := i.(T)
Copy after login

This expression can assert an interface object (i) It is not nil, and the type of the value stored in the interface object (i) is T. If the assertion succeeds, the value will be returned to t. If the assertion fails, panic will be triggered.

Let’s write a piece of code to test it

package main

import "fmt"

func main() {
    var i interface{} = 10
    t1 := i.(int)
    fmt.Println(t1)

    fmt.Println("=====分隔线=====")

    t2 := i.(string)
    fmt.Println(t2)
}
Copy after login

The output after running is as follows. You can find that it failed when executing the second assertion and triggered panic

10
=====分隔线=====
panic: interface conversion: interface {} is int, not string

goroutine 1 [running]:
main.main()
        E:/GoPlayer/src/main.go:12 +0x10e
exit status 2
Copy after login

If you want The asserted interface value is nil, so let’s see if it will trigger panic as expected

package main

func main() {
    var i interface{} // nil
    var _ = i.(interface{})
}
Copy after login

The output is as follows, it will indeed trigger panic

panic: interface conversion: interface is nil, not interface {}

goroutine 1 [running]:
main.main()
        E:/GoPlayer/src/main.go:5 +0x34
exit status 2
Copy after login

Second type

t, ok:= i.(T)
Copy after login

Same as above, this expression can also assert that an interface object (i) is not nil, and the type of the value stored in the interface object (i) is T. If the assertion is successful, it will be returned Its type is t, and the value of ok is true at this time, indicating that the assertion is successful.

If the type of the interface value is not the T we asserted, the assertion will fail, but unlike the first expression, this will not trigger panic, but will set the value of ok to false , indicating that the assertion failed, and t is the zero value of T at this time.

Slightly modify the above example, as follows

package main

import "fmt"

func main() {
    var i interface{} = 10
    t1, ok := i.(int)
    fmt.Printf("%d-%t\n", t1, ok)

    fmt.Println("=====分隔线1=====")

    t2, ok := i.(string)
    fmt.Printf("%s-%t\n", t2, ok)

    fmt.Println("=====分隔线2=====")

    var k interface{} // nil
    t3, ok := k.(interface{})
    fmt.Println(t3, "-", ok)

    fmt.Println("=====分隔线3=====")
    k = 10
    t4, ok := k.(interface{})
    fmt.Printf("%d-%t\n", t4, ok)

    t5, ok := k.(int)
    fmt.Printf("%d-%t\n", t5, ok)
}
Copy after login

The output after running is as follows. It can be found that when the second assertion was executed, although it failed, it did not trigger a panic.

10-true
=====分隔线1=====
-false
=====分隔线2=====
<nil> - false
=====分隔线3=====
10-true
10-true
Copy after login

In the above output, you should pay attention to that the output of the second assertion before -false is not whether there is any value of t2 output, but because the assertion failed, so What t2 gets is that the zero value of the string is also "", which is zero length, so you can't see its output.

Type Switch

If you need to distinguish between multiple types, you can use type switch assertions. This will be simpler, more direct, and more efficient than making type assertions one by one.

package main

import "fmt"

func findType(i interface{}) {
    switch x := i.(type) {
    case int:
        fmt.Println(x, "is int")
    case string:
        fmt.Println(x, "is string")
    case nil:
        fmt.Println(x, "is nil")
    default:
        fmt.Println(x, "not type matched")
    }
}

func main() {
    findType(10)      // int
    findType("hello") // string

    var k interface{} // nil
    findType(k)

    findType(10.23) //float64
}
Copy after login

The output is as follows

10 is int
hello is string
<nil> is nil
10.23 not type matched
Copy after login

Extra explanation:

  • If your value is nil, then the match is case nil
  • If your value does not match the corresponding type in switch-case, then the default branch is taken

[Related recommendations: Go video tutorial,Programming Teaching

The above is the detailed content of What is type assertion in go language?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

How to ensure concurrency is safe and efficient when writing multi-process logs? How to ensure concurrency is safe and efficient when writing multi-process logs? Apr 02, 2025 pm 03:51 PM

Efficiently handle concurrency security issues in multi-process log writing. Multiple processes write the same log file at the same time. How to ensure concurrency is safe and efficient? This is a...

Do I need to install an Oracle client when connecting to an Oracle database using Go? Do I need to install an Oracle client when connecting to an Oracle database using Go? Apr 02, 2025 pm 03:48 PM

Do I need to install an Oracle client when connecting to an Oracle database using Go? When developing in Go, connecting to Oracle databases is a common requirement...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles