Home  >  Article  >  Backend Development  >  What scenarios is golang reflection used for?

What scenarios is golang reflection used for?

angryTom
angryTomOriginal
2020-03-14 14:47:544205browse

What scenarios is golang reflection used for?

What scenarios is golang reflection used for?

1. The most common usage scenario of reflection in golang is serialization of objects (serialization, sometimes called Marshal & Unmarshal).

For example, the Go language standard library's encoding/json, encoding/xml, encoding/gob, encoding/binary and other packages rely heavily on reflection functions.

Related recommendations: golang tutorial

Most of the time, variables, types and functions in Go are very simple and straightforward. When you need a type, variable or function, you can define them directly:

type Foo struct {
 A int
 B string
}
 
var x Foo
 
func DoSomething(f Foo) {
 fmt.Println(f.A, f.B)
}

2. But sometimes you want to use the variable's information at runtime that does not exist when you write the program. Say you're trying to map data from a file or network request into variables. Or you want to build a tool that works for a different type of application.

In this case you need to use reflection. Reflection enables you to check types at runtime. It also allows you to inspect, modify and create variables, functions and structures at runtime.

Reflection in Go is built on three concepts:

Types, Kinds and Values ​​(Types Kinds Values).

PHP Chinese website, a large number of programming tutorials and thinkphp tutorials, welcome to learn.

The above is the detailed content of What scenarios is golang reflection used for?. 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