In Go, each variable consists of two parts: type and value.
A type is a compile-time property that defines the type of data that a variable can store and the operations that can be performed on this data. Values are the data of the variable at runtime.
use
The easiest and most direct way, throughof
%T
Print the type of variable.
func main() { var x float64 = 3.4 ("Type of x: %T\n", x) }
Output:
Type of x: float64
This method is simple and direct, and is very suitable for use during the code debugging stage.
Type selection
Type assertion detection variable types are provided in Go, which is a way to type checking and conversion provided in Go.
The example is as follows:
func main() { var i interface{} = "Hello" // Type assertion s, ok := i.(string) if ok { (s) } }
Output:
Hello
This method is mainly used to convert variables into supported specific types when a variable type is known. Of course, it is particularly noted that this is not a forced type conversion.
Type selection
Type selection is similar to type inference and is also a way of type checking and conversion provided in Go.
func main() { var i interface{} = "Hello" // Type selection switch v := i.(type) { case string: (v) // case int: (v * 2) default: ("Unknown type") } }
Output:
Hello
When GO does not support generics, type selection is often used tointerface{}
Interface coordination implements generic-like functions.
reflection
We can also passFunction returns the type object of the variable
, which represents the type of its parameter.
For ordinary types, we can directly obtain the types through the following code:
func main() { var x float64 = 3.4 ("Type of x:", (x)) }
Output:
Type of x: float64
For structure variables, to get the variable type, the example code is as follows:
type Person struct { Name string Age int } func main() { p := Person{"John Doe", 30} t := (p) ("Type of p:", t) // Type of output structure // traverse all fields in the structure for i := 0; i < (); i++ { field := (i) ("Field Name: '%s', Field Type: '%s'\n", , ) } }
Output:
Type of p:
Field Name: 'Name', Field Type: 'string'
Field Name: 'Age', Field Type: 'int'
We obtained type information including each field in it.
Relative to, type assertions and type selection, reflection provides more capabilities in the Go language, such as the ability to check and modify variable types and values at runtime, allowing developers to dynamically obtain type information, access structure fields, call methods, and operate slices and maps, but these operations may affect the performance of the program.
This is the end of this article about the method of obtaining variable types in golang. For more related content on obtaining variable types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!