Table of Contents
What is reflection" >What is reflection
Reflection (reflect package)" >Reflection (reflect package)
示例代码" >示例代码
函数" >函数
main
" >main
执行结果
" >执行结果
TypeOf 的Name和Kind" >TypeOf 的Name和Kind
结构体
" >结构体
总结
" >总结
ValueOf" >ValueOf
通过反射设置值
" >通过反射设置值
Home Backend Development Golang An article teaches you the basics of reflection in Go language

An article teaches you the basics of reflection in Go language

Jul 25, 2023 pm 05:01 PM
go language

What is reflection

Reflection, um..., means reverse, that is, turning things over.

For example, a very simple code like this.

var a int = 3
fmt.Println(a)
Copy after login

Of course we know that the avariable isint type, but thinking about it the other way around, how does the program know that a is What about the int type? ? ?

At this time, you need to use reflection.

Sample code

v := reflect.TypeOf(a)
fmt.Println(v)
Copy after login

The two codes are combined into one execution result

An article teaches you the basics of reflection in Go language

The second line of code successfully restored the variable a to int type.

What? ? ? What use are you to me? ? ? ,Um. . . To be honest, I don’t use it too much, but I have to know how to do it.


Reflection (reflect package)

In Go, any variable , both have concrete types and concrete values ​​, just like var a int = 3, The specific type is int, The specific value is 3.

So, the specific type of the variable belongs to reflect.Type , the specific value of the variable belongs to reflect.Value.

And Go provides

  • ##reflect.TypeOf Get the specific type.

  • ##reflect.ValueOfGet the specific value.

TypeOf

##TypeOf

method can get the # of the variable ##Specific type. There is a need to define a function that can receive any type of data and print the variable type through reflection.

示例代码

函数

func reflectType(x interface{}) {
    v := reflect.TypeOf(x)
    fmt.Printf("你传入的变量类型是:%v\n",v)
}
Copy after login

main

func main() {
    var a int = 666
    var b float64 = 3.14
    var c string = "hello world"
    var d [3]int = [3]int{1,2,6}
    var e []int = []int{1,2,6,88}
    var f map[string]interface{} = map[string]interface{}{
        "Name":"张三",
        "Age":18,
}
    reflectType(a)
    reflectType(b)
    reflectType(c)
    reflectType(d)
    reflectType(e)
    reflectType(f)
}
Copy after login

执行结果

An article teaches you the basics of reflection in Go language

通过reflect.TypeOf方法,完美解决上述需求。

TypeOf 的Name和Kind

这个是啥意思呢??这个在结构体中比较好体现。

简答来说就是TypeOf返回的太笼统了,还有更加细化的类型,通过这俩属性获取。

示例代码

函数
func reflectType(x interface{}) {
v := reflect.TypeOf(x)
fmt.Printf("你传入的变量类型是:%v | Name:%v | Kind:%v\n", v, v.Name(), v.Kind())
}
Copy after login
结构体
type Student struct {
    Name string
    Age int
}
Copy after login
main
func main() {
    var a int
    var b *int
    var c []int
    var d map[string]interface{}
    var e Student
    reflectType(a)
    reflectType(b)
    reflectType(c)
    reflectType(d)
    reflectType(e)
}
Copy after login

执行结果

An article teaches you the basics of reflection in Go language

总结

经过对比,会发现几个特殊问题。

如果变量是指针类型Name为空,Kindptr

If the variable is a reference type (slice and map) type, Name is empty, only Kind.

If the variable is a structure, Name is the structure name, Kind is struct.

ValueOf

TypeOf can only get the ## of the variable in reverse #Specific type, but you cannot get the specific value, which is a bit unkind.

所以ValueOf就来解决这个问题了,但是ValueOf牛叉的是,它里面还包括了变量类型

注:ValueOfTypeOfKind属性返回内容是一摸一样的。

需求:定义一个函数,可以接收任意类型,通过反射得出变量类型和变量值。

函数

func reflectType(x interface{}) {
    v := reflect.ValueOf(x)
    k := v.Kind()
    switch k {
    case reflect.Int:
        fmt.Printf("我是Int类型,我的值是%v\n",v.Int())
    case reflect.Slice:
        fmt.Printf("我是切片类型,我的值是%v\n",v.Slice(1,2))
    case reflect.Map:
        fmt.Printf("我是切片类型,我的值是%v\n",v.MapKeys())
    //case :可以继续case下去
  }
}
Copy after login

main

func main() {
  var a int = 1
  var c []int = []int{1, 5, 7, 19}
  var d map[string]interface{} = map[string]interface{}{
    "Name": "你好",
    "Age":  18,
  }
  var e Student
  reflectType(a)


  reflectType(c)
  reflectType(d)
  reflectType(e)
}
Copy after login

执行结果

An article teaches you the basics of reflection in Go language

通过反射设置值

反射还有一个用途,就是动态的修改变量值,可能你暂时体会不到,但是语法还是要学的。

通过反射设置值,需要用到Elem方法,并且传入的必须是指针

示例代码

函数

func reflectSetValue(x interface{}) {
  v := reflect.ValueOf(x)
  //kind也必须是Elem调用
  var k = v.Elem().Kind()
  switch k {
  case reflect.Int:
    //反射修改必须通过Elem
    v.Elem().SetInt(200)
  }
}
Copy after login

main

func main() {
  var a int = 10
  fmt.Printf("a的值:%v\n", a)
  //反射修改值传入的必须是地址
  reflectSetValue(&a)
  fmt.Printf("a的值:%v\n", a)
}
Copy after login

执行结果

An article teaches you the basics of reflection in Go language

Summary

We have learned the basic reflection of GoTypeOf, Name and Kind of TypeOf,ValueOf, Set the value via reflection.

whereKind is in Type# Both ## and ValueOf are available, usually TypeOf and ValueOfUse together for better results!

Reflection may not be easy to understand, so you must work harder! persist in! !

The above is the detailed content of An article teaches you the basics of reflection in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles