Go language reflection is an introspection mechanism, implemented through the reflect package, that allows a program to inspect and modify its own structures, fields, and methods. Using reflection, you can obtain reflection objects of types and values, inspect types, access and modify fields, and call methods. One practical application is to use reflection to perform unified operations on different types that implement a specific interface, such as the Number interface in the summation example.
Reflection in Go language: clever use
Reflection is an introspection mechanism that allows a program to inspect and modify itself structure, fields and methods. In the Go language, reflection is implemented through the reflect
package.
Basic usage
The basis of reflection is the type reflect.Type
and the value reflect.Value
. reflect.Type
represents a Go type, while reflect.Value
represents a specific value. To get the reflect.Type
of a type, you can use the reflect.TypeOf()
function:
type Person struct { Name string Age int } p := Person{"John", 30} typ := reflect.TypeOf(p)
To get the reflect.Value## of a value #, you can use
reflect.ValueOf() Function:
v := reflect.ValueOf(p)
Check the type
Using reflection, we can check the type of the value:fmt.Println(typ.Name()) // 输出: Person fmt.Println(v.Kind()) // 输出: struct
Access fields
You can use thereflect.Value.Field() method to access the fields of the structure. This method returns a
reflect.Value, indicating the value of the field:
nameField := v.FieldByName("Name") fmt.Println(nameField.String()) // 输出: John
Modify the field
throughreflect.Value.Set( ) method, you can also modify the fields of the structure:
nameField.SetString("Alice") fmt.Println(p.Name) // 输出: Alice
Method call
Reflection also allows calling methods. Use thereflect.Value.Method() method to get a method object, and then use the
reflect.Method.Call() method to call it:
ageMethod := v.MethodByName("GetAge") result := ageMethod.Call([]reflect.Value{}) fmt.Println(result[0].Int()) // 输出: 30
Practical combat Case
The following is an actual case using reflection:type Number interface { Int() int } func Sum(numbers []Number) int { total := 0 v := reflect.ValueOf(numbers) for i := 0; i < v.Len(); i++ { total += v.Index(i).MethodByName("Int").Call([]reflect.Value{})[0].Int() } return total } type IntNumber int func (n IntNumber) Int() int { return int(n) } type FloatNumber float64 func (n FloatNumber) Int() int { return int(n) } func main() { numbers := []Number{IntNumber(4), FloatNumber(5.3), IntNumber(6)} fmt.Println(Sum(numbers)) // 输出: 15 }In this case, we define a
Number interface and some types that implement it. The
Sum() function uses reflection to call the
Int() method on all values of type
Number in the slice, and sums the results.
The above is the detailed content of Clever use of reflection in Go language. For more information, please follow other related articles on the PHP Chinese website!

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

Article discusses iterating through maps in Go, focusing on safe practices, modifying entries, and performance considerations for large maps.Main issue: Ensuring safe and efficient map iteration in Go, especially in concurrent environments and with l

The article discusses creating and manipulating maps in Go, including initialization methods and adding/updating elements.

The article discusses differences between arrays and slices in Go, focusing on size, memory allocation, function passing, and usage scenarios. Arrays are fixed-size, stack-allocated, while slices are dynamic, often heap-allocated, and more flexible.

The article discusses creating and initializing slices in Go, including using literals, the make function, and slicing existing arrays or slices. It also covers slice syntax and determining slice length and capacity.

The article explains how to create and initialize arrays in Go, discusses the differences between arrays and slices, and addresses the maximum size limit for arrays. Arrays vs. slices: fixed vs. dynamic, value vs. reference types.

Article discusses syntax and initialization of structs in Go, including field naming rules and struct embedding. Main issue: how to effectively use structs in Go programming.(Characters: 159)

The article explains creating and using pointers in Go, discussing benefits like efficient memory use and safe management practices. Main issue: safe pointer use.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
