What are type assertions in Go language?
Jun 11, 2023 am 08:56 AMGo 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)
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 類型。 ") }
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)
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("類型斷言失敗。 ") } }
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Laravel supports the use of native SQL queries, but parameter binding should be preferred to ensure safety; 1. Use DB::select() to execute SELECT queries with parameter binding to prevent SQL injection; 2. Use DB::update() to perform UPDATE operations and return the number of rows affected; 3. Use DB::insert() to insert data; 4. Use DB::delete() to delete data; 5. Use DB::statement() to execute SQL statements without result sets such as CREATE, ALTER, etc.; 6. It is recommended to use whereRaw, selectRaw and other methods in QueryBuilder to combine native expressions to improve security

Go generics are supported since 1.18 and are used to write generic code for type-safe. 1. The generic function PrintSlice[Tany](s[]T) can print slices of any type, such as []int or []string. 2. Through type constraint Number limits T to numeric types such as int and float, Sum[TNumber](slice[]T)T safe summation is realized. 3. The generic structure typeBox[Tany]struct{ValueT} can encapsulate any type value and be used with the NewBox[Tany](vT)*Box[T] constructor. 4. Add Set(vT) and Get()T methods to Box[T] without

json.loads() is used to parse JSON strings into Python data structures. 1. The input must be a string wrapped in double quotes and the boolean value is true/false; 2. Supports automatic conversion of null→None, object→dict, array→list, etc.; 3. It is often used to process JSON strings returned by API. For example, response_string can be directly accessed after parsing by json.loads(). When using it, you must ensure that the JSON format is correct, otherwise an exception will be thrown.

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

@property decorator is used to convert methods into properties to implement the reading, setting and deletion control of properties. 1. Basic usage: define read-only attributes through @property, such as area calculated based on radius and accessed directly; 2. Advanced usage: use @name.setter and @name.deleter to implement attribute assignment verification and deletion operations; 3. Practical application: perform data verification in setters, such as BankAccount to ensure that the balance is not negative; 4. Naming specification: internal variables are prefixed, property method names are consistent with attributes, and unified access control is used to improve code security and maintainability.

Use the uuid module to obtain the MAC address of the first network card of the machine across the platform, without the need for a third-party library, and convert it into a standard format through uuid.getnode(); 2. Use subprocess to call system commands such as ipconfig or ifconfig, and combine it with regular extraction of all network card MAC addresses, which is suitable for scenarios where multiple network card information needs to be obtained; 3. Use the third-party library getmac, call get_mac_address() after installation to obtain the MAC, which supports query by interface or IP, but requires additional dependencies; in summary, if no external library is needed, the uuid method is recommended. If you need to flexibly obtain multi-network card information, you can use the subprocess solution to allow you to install the dependency getma.
