Home Backend Development Golang What are type assertions in Go language?

What are type assertions in Go language?

Jun 11, 2023 am 08:56 AM
programming go language type assertion

Go language is a statically typed programming language. Type assertion (Type Assertion) is one of the ways to determine the specific value type stored in the interface variable in the program. In the Go language, an interface variable can store any type of value, but the type information stored in the interface variable is limited, and all types of operations cannot be performed on the interface variable. Therefore, in actual applications, we need to judge and convert the specific value types stored in interface variables. This is what type assertions do.

Type assertions in the Go language come in two forms: value type assertions and pointer type assertions. Value type assertions and pointer type assertions have slightly different ways of judging and converting the value types of interface variables.

Value type assertion:

The syntax format of value type assertion is as follows:

x.(T)
Copy after login

Among them, x is a variable of interface type, and T represents a specific type. This type assertion is true if x stores a value of type T, and false otherwise.

The result of the type assertion has two values. The first value is the value after x is converted to type T. The second value is a Boolean value indicating whether the result of this type assertion is true. The specific code implementation is as follows:

var x interface{}
x = "hello"

s, ok := x.(string)
if ok {
    fmt.Printf("x 类型为 string,值为 %s。
", s)
} else {
    fmt.Printf("x 不是 string 类型。
")
}
Copy after login

In the above code, an empty interface type variable x is first defined, and a string "hello" is assigned to the variable x. The value type assertion statement x.(string) attempts to convert the variable x to a string type, s represents the converted string, and ok represents whether the type assertion is successful. If ok is true, it means that the value type stored in x is a string type, and we can output the converted string s. If ok is false, it means that x is not a string type and the corresponding prompt information can be output.

Pointer type assertion:

The syntax format of pointer type assertion is similar to that of value type assertion, except that the pointer needs to be operated when asserting.

x.(*T)
Copy after login

Among them, *T represents the pointer type of type T. This type assertion is true if the value stored in x is of pointer type T, and false otherwise.

Like value type assertions, pointer type assertions also have two values. The first value is the value after x is converted into a T type pointer. The second value is a Boolean value, indicating the type assertion. Whether the result is true. The specific code implementation is as follows:

type Foo struct {
    bar string
}

func main() {
    var i interface{} = &Foo{"hello"}

    f, ok := i.(*Foo)
    if ok {
        fmt.Printf("i 是指针类型,指向 Foo 类型的变量,f.bar 的值为 %s。
", f.bar)
    } else {
        fmt.Printf("类型断言失败。
")
    }
}
Copy after login

In the above code, a structure of type Foo is defined, an empty interface variable i is defined in the main function, and a structure pointing to type Foo is defined The pointer is assigned to variable i. Pointer type assertion x.(*Foo) attempts to convert variable x into a pointer type pointing to a structure of type Foo, f represents the converted pointer, and ok represents whether the type assertion is successful. If ok is true, it means that the value type stored in x is a pointer type pointing to a Foo type structure, and we can output the field value in the structure pointed to by the pointer. If ok is false, it means that x is not a pointer type pointing to a Foo type structure, and the corresponding prompt information can be output.

Summary:

Type assertion is a commonly used way to operate interface variables in the Go language. Type assertions can determine the type stored in the interface variable, and then make corresponding adjustments to it. operate. There are two forms of type assertions in Go language, value type assertions and pointer type assertions. When using type assertions, you need to pay attention to error handling to avoid runtime errors.

The above is the detailed content of What are type assertions 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

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...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

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, ...

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 is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

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