Go反射四讲---第一讲:什么是反射,反射常用的API,反射三原则以及注意事项

2024-08-25 10:28

本文主要是介绍Go反射四讲---第一讲:什么是反射,反射常用的API,反射三原则以及注意事项,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

反射-引入

这是我们反射四讲的第一讲,本次主要向大家介绍一下反射的基础概念以及相关的API。

在计算机科学中,反射是指计算机程序能够在运行时可以访问,检测和修改本身状态或者行为的一种能力。

简单的来说,反射就是程序在运行时能够动地查看自己的状态,并允许修改自身的行为。

首先,要明白对于一个类型变量。它有两层含义,一是类型是什么,二是存储的值是什么。类型决定了变量的存储方式,支持的操作和方法等。值无外乎是读与写,在存储是以0,1格式存放,并使用类型加以约束。类型和值不是孤立存在的。

反射的相关API都在 reflect 包中,最核心的就是reflect.Valuereflect.Type
其中,reflect.Value用于操作值,部分值是可以被反射修改的。reflect.Type用于操作类型信息。类型信息是只能读取的。

注意:reflect.Type可以通过reflect.Value得到,但是反过来不行。

reflect.Type

func TypeOf(i any) Type
//type any = interface{}

形参是一个空接口类型,返回值是一个 Type 接口类型。

注意:reflect包有一个很强的的假设,我们必须我们要操作的是什么Kind

Kind是一个枚举值,用来判断操作的对应类型。例如是否是指针,是否是数组,是否是切片等。
如果使用不当就会引起 panic。so,在调用API之前,我们一定要先读注释,确认什么情况下可以使用!!!

接下来,讲解一下 Type 接口提供的主要通用方法。

类型的通用方法

// Name returns the type's name within its package for a defined type.
Name() string// Kind returns the specific kind of this type.
Kind() Kind// Implements reports whether the type implements the interface type u.
Implements(u Type) bool// AssignableTo reports whether a value of the type is assignable to type u.
AssignableTo(u Type) bool// ConvertibleTo reports whether a value of the type is convertible to type u.
ConvertibleTo(u Type) bool// Comparable reports whether values of this type are comparable.
Comparable() bool// NumMethod returns the number of methods accessible using Method.
NumMethod() int// Method returns the i'th method in the type's method set.
Method(int) Method// MethodByName returns the method with that name in the type's
// method set and a boolean indicating if the method was found.
MethodByName(string) (Method, bool)// PkgPath returns a defined type's package path, that is, the import path
PkgPath() string// Size returns the number of bytes needed to store
Size() uintptr

类型的专有方法

type Type interface {
// Elem returns a type's element type.
// It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice.
Elem() Type// Bits returns the size of the type in bits.
Bits() int// Len returns an array type's length.
// It panics if the type's Kind is not Array.
Len() int// struct 专有的方法// NumField returns a struct type's field count.
// It panics if the type's Kind is not Struct.
NumField() int// Field returns a struct type's i'th field.
// It panics if the type's Kind is not Struct.
// It panics if i is not in the range [0, NumField()).
Field(i int) StructField// FieldByIndex returns the nested field corresponding
// to the index sequence. It is equivalent to calling Field
// successively for each index i.
// It panics if the type's Kind is not Struct.
FieldByIndex(index []int) StructField// FieldByName returns the struct field with the given name
// and a boolean indicating if the field was found.
// If the returned field is promoted from an embedded struct,
// then Offset in the returned StructField is the offset in
// the embedded struct.
FieldByName(name string) (StructField, bool)// FieldByNameFunc returns the struct field with a name
// that satisfies the match function and a boolean indicating if
// the field was found.
FieldByNameFunc(match func(string) bool) (StructField, bool)// func 专有的方法// IsVariadic reports whether a function type's final input parameter
// IsVariadic panics if the type's Kind is not Func.
IsVariadic() bool// In returns the type of a function type's i'th input parameter.
// It panics if the type's Kind is not Func.
// It panics if i is not in the range [0, NumIn()).
In(i int) Type// NumIn returns a function type's input parameter count.
// It panics if the type's Kind is not Func.
NumIn() int// NumOut returns a function type's output parameter count.
// It panics if the type's Kind is not Func.
NumOut() int// map 专有的方法// Key returns a map type's key type.
// It panics if the type's Kind is not Map.
Key() Type
}

reflect.Value

reflect.Value 表示的是实例的值信息。reflect.Value是一个 struct,并且提供了一系列的 method

func ValueOf(i any) Value
//type Value struct {
//	typ_ *abi.Type  //值的指针类型typ
//	ptr unsafe.Pointer // 指向值的指针ptr
//	flag //标记字段
//}

注意:这里一定要搞清与Type的区别,Type 直接返回接口,Value 返回的是结构体,而在结构体上绑定了一些方法。

下面我们介绍几个常用的在 Value 结构体上绑定的方法。

// CanAddr reports whether the value's address can be obtained with [Value.Addr].
func (v Value) CanAddr() bool {}// Addr returns a pointer value representing the address of v.
func (v Value) Addr() Value {}// CanSet reports whether the value of v can be changed.
func (v Value) CanSet() bool {}// Elem returns the value that the interface v contains
// or that the pointer v points to.
func (v Value) Elem() Value {}// Field returns the i'th field of the struct v.
func (v Value) Field(i int) Value {}// Bool returns v's underlying value.
func (v Value) Bool() bool {}// Bytes returns v's underlying value.
func (v Value) Bytes() []byte {} // Index returns v's i'th element.
func (v Value) Index(i int) Value {}

这里方法我们没有讲解全面,如果想了解源码内容,可以去 reflect 包下的 value.go 下查看。

反射的原则

下图展示了实例,Type与Value三者之间的关系。

API使用总结:

  1. 实例到 Value。使用实例获取对象的 Value,直接使用 reflect.ValueOf() 函数。

  2. 实例到 Type。使用实例获取对象的 Type, 直接使用 reflect.TypeOf()函数。

  3. TypeValue。无法直接从一个 Type 接口变量获取实例的 Value。一般先使用 Type 构建一个新的实例Value

    第一种,使用func New(typ Type) Value创建一个ValueValueType是一个指定的typ的指针类型。

    第二种,使用func Zero(typ Type) Value创建一个Value,注意此时的Value不能寻址,意味着值不可以变。

    第三种,如果知道一个值的底层存放地址,可以使用func NewAt(typ Type, p unsafe.Pointer) Value来恢复Value。此处的typ是实例类型,p是实例的地址。

  4. ValueType。直接可以调用Value结构体上绑定的func (v Value) Type() Type {}方法。

  5. Value 到实例。可以使用通用方法func (v Value) Interface() (i any) {}直接返回实例。

  6. Value指针到值。使用func (v Value) Elem() Value {}返回值。注意:如果类型是接口,则 Elem()返回接口绑定的实例的 Value ,如果类型是指针,则返回指针值的 Value ,否则引起 panic

  7. Type指针到Type值。使用Elem() Type返回子元素的Type

  8. Type值到Type指针。使用func PtrTo(t Type) Type {},返回指向t的指针类型Type

  9. 值的可修改性。可以使用func (v Value) CanSet() bool {}去判断一个值是否可以修改,如果可以修改返回true。接着可以使用func (v Value) Set(x Value)去设置一个值。

总结

本次,带领大家了解反射的基本概念,如何使用等。待熟悉相关的API之后,下一次,我们将展示给您如何在实战中使用reflect包。

参考

  • 《Go语言核心编程》-- 李文塔
  • https://pkg.go.dev/reflect

这篇关于Go反射四讲---第一讲:什么是反射,反射常用的API,反射三原则以及注意事项的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1105302

相关文章

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Go语言中泄漏缓冲区的问题解决

《Go语言中泄漏缓冲区的问题解决》缓冲区是一种常见的数据结构,常被用于在不同的并发单元之间传递数据,然而,若缓冲区使用不当,就可能引发泄漏缓冲区问题,本文就来介绍一下问题的解决,感兴趣的可以了解一下... 目录引言泄漏缓冲区的基本概念代码示例:泄漏缓冲区的产生项目场景:Web 服务器中的请求缓冲场景描述代码

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

Go语言中Recover机制的使用

《Go语言中Recover机制的使用》Go语言的recover机制通过defer函数捕获panic,实现异常恢复与程序稳定性,具有一定的参考价值,感兴趣的可以了解一下... 目录引言Recover 的基本概念基本代码示例简单的 Recover 示例嵌套函数中的 Recover项目场景中的应用Web 服务器中

Java反射实现多属性去重与分组功能

《Java反射实现多属性去重与分组功能》在Java开发中,​​List是一种非常常用的数据结构,通常我们会遇到这样的问题:如何处理​​List​​​中的相同字段?无论是去重还是分组,合理的操作可以提高... 目录一、开发环境与基础组件准备1.环境配置:2. 代码结构说明:二、基础反射工具:BeanUtils

Java使用MethodHandle来替代反射,提高性能问题

《Java使用MethodHandle来替代反射,提高性能问题》:本文主要介绍Java使用MethodHandle来替代反射,提高性能问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录一、认识MethodHandle1、简介2、使用方式3、与反射的区别二、示例1、基本使用2、(重要)