search
HomeBackend DevelopmentGolangClever use of reflection in Go language

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.

Go 语言中的反射巧妙运用

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 the

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

through

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

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

Statement
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
Interfaces and Polymorphism in Go: Achieving Code ReusabilityInterfaces and Polymorphism in Go: Achieving Code ReusabilityApr 29, 2025 am 12:31 AM

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

How do you iterate through a map in Go?How do you iterate through a map in Go?Apr 28, 2025 pm 05:15 PM

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

How do you create a map in Go?How do you create a map in Go?Apr 28, 2025 pm 05:14 PM

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

What is the difference between an array and a slice in Go?What is the difference between an array and a slice in Go?Apr 28, 2025 pm 05:13 PM

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.

How do you create a slice in Go?How do you create a slice in Go?Apr 28, 2025 pm 05:12 PM

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.

How do you create an array in Go?How do you create an array in Go?Apr 28, 2025 pm 05:11 PM

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.

What is the syntax for creating a struct in Go?What is the syntax for creating a struct in Go?Apr 28, 2025 pm 05:10 PM

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)

How do you create a pointer in Go?How do you create a pointer in Go?Apr 28, 2025 pm 05:09 PM

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

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

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