当前位置: 首页 > news >正文

Go语言高阶:Reflection反射与Files操作 详细示例教程

目录标题

  • 一、Reflection反射
    • 1. What is reflection? 什么是反射
    • 2. Inspect a variable and find its type 检查变量并找到它的类型
    • 3. Reflect.Type and reflect.Value 反射类型和值
    • 4. Reflect.Kind 查看底层种类
    • 5. NumField() and Field() methods 字段数量和索引值方法
    • 6. Int() and String() methods 整型和字符型方法
    • 7. Complete Program 完整示例
  • 二、 Reading Files
    • 1. Reading Files 读取文件
    • 2. Using absolute file path 使用绝对路径
    • 3. Passing the file path as a command line flag 将文件路径作为命令行标志传递
    • 4. Reading a file in small chunks
    • 5. Reading a file line by line 逐行读取文件

一、Reflection反射

1. What is reflection? 什么是反射

	反射是Go中的高级主题之一,在Go语言中反射(reflection)是指在程序运行时动态地检查类型信息和操作对象的能力。通过反射,你可以在运行时获取类型的信息,访问和修改对象的字段和方法,以及动态地调用函数。 Go语言中的反射由reflect包提供支持。该包中的Type和Value类型提供了访问和操作类型和对象的方法。要使用反射,首先需要使用reflect.TypeOf()函数获取一个值的类型信息,或者使用reflect.ValueOf()函数获取一个值的反射对象。这些函数返回的类型对象或值对象包含了有关值的类型、字段、方法等信息。反射对象的常用方法包括:Type.Kind():返回类型的种类,如整数、字符串、结构体等。Type.Name():返回类型的名称。Type.Field(i int):返回结构体类型的第i个字段的反射对象。Type.NumField():返回结构体类型的字段数量。Value.Interface():将反射对象转换为普通的接口类型。Value.Kind():返回值的种类,如整数、字符串、结构体等。Value.String():返回值的字符串表示。Value.Field(i int):返回结构体类型值的第i个字段的反射对象。Value.NumField():返回结构体类型值的字段数量。Value.Method(i int):返回值的第i个方法的反射对象。Value.Call(args []Value):调用值对应的方法,传递参数并返回结果。通过使用这些方法,你可以在运行时检查和操作任意类型的对象。例如,你可以获取一个结构体类型的字段名和值,动态调用函数,或者创建新的对象。

2. Inspect a variable and find its type 检查变量并找到它的类型

        package mainimport ("fmt")type order struct {ordId      intcustomerId int}type employee struct {name    stringid      intaddress stringsalary  intcountry string}func createQuery(b order) string {i := fmt.Sprintf("insert into order values(%d, %d)", b.ordId, b.customerId)return i}func createQuerySet(b employee) string {i := fmt.Sprintf("insert into order values(%s, %d, %s, %d, %s)", b.name, b.id, b.address, b.salary, b.country)return i}func main() {a := 10fmt.Printf("%d, %T\n", a, a)b := order{171103,1006,}e := employee{"Like",1,"Shanghai",999999,"Minghang",}fmt.Println(createQuery(b))fmt.Println(createQuerySet(e))}// 10, int// insert into order values(171103, 1006)// insert into order values(Like, 1, Shanghai, 999999, Minghang)

3. Reflect.Type and reflect.Value 反射类型和值

        package mainimport (  "fmt""reflect")type order struct {  ordId      intcustomerId int}func createQuery(q interface{}) {  t := reflect.TypeOf(q)v := reflect.ValueOf(q)fmt.Println("Type ", t)fmt.Println("Value ", v)}func main() {  o := order{ordId:      456,customerId: 56,}createQuery(o)}// Type  main.order  // Value  {456 56}  

4. Reflect.Kind 查看底层种类

        package mainimport (  "fmt""reflect")type order struct {  ordId      intcustomerId int}func createQuery(q interface{}) {  t := reflect.TypeOf(q)k := t.Kind()fmt.Println("Type ", t)fmt.Println("Kind ", k)}func main() {  o := order{ordId:      456,customerId: 56,}createQuery(o)}// Type  main.order  // Kind  struct  

5. NumField() and Field() methods 字段数量和索引值方法

        package mainimport (  "fmt""reflect")type order struct {  ordId      intcustomerId int}func createQuery(q interface{}) {   if reflect.ValueOf(q).Kind() == reflect.Struct {	// struct == structv := reflect.ValueOf(q) 	// {456 56}fmt.Println("Number of fields", v.NumField())		// 2for i := 0; i < v.NumField(); i++ {fmt.Printf("Field:%d type:%T value:%v\n", i, v.Field(i), v.Field(i))}}}func main() {  o := order{ordId:      456,customerId: 56,}createQuery(o)}// Number of fields 2  // Field:0 type:reflect.Value value:456  // Field:1 type:reflect.Value value:56  

6. Int() and String() methods 整型和字符型方法

        package mainimport (  "fmt""reflect")func main() {  a := 56x := reflect.ValueOf(a).Int()fmt.Printf("type:%T value:%v\n", x, x)b := "Naveen"y := reflect.ValueOf(b).String()fmt.Printf("type:%T value:%v\n", y, y)}// type:int64 value:56  // type:string value:Naveen  

7. Complete Program 完整示例

        package mainimport (  "fmt""reflect")type order struct {  ordId      intcustomerId int}type employee struct {  name    stringid      intaddress stringsalary  intcountry string}func createQuery(q interface{}) {  if reflect.ValueOf(q).Kind() == reflect.Struct {t := reflect.TypeOf(q).Name()query := fmt.Sprintf("insert into %s values(", t)		// 输出传入的valuesv := reflect.ValueOf(q)		// 赋值vfor i := 0; i < v.NumField(); i++ {switch v.Field(i).Kind() {case reflect.Int:if i == 0 {query = fmt.Sprintf("%s%d", query, v.Field(i).Int())} else {query = fmt.Sprintf("%s, %d", query, v.Field(i).Int())}case reflect.String:if i == 0 {query = fmt.Sprintf("%s\"%s\"", query, v.Field(i).String())} else {query = fmt.Sprintf("%s, \"%s\"", query, v.Field(i).String())}default:fmt.Println("Unsupported type")return}}query = fmt.Sprintf("%s)", query)fmt.Println(query)return}fmt.Println("unsupported type")}func main() {  o := order{ordId:      456,customerId: 56,}createQuery(o)e := employee{name:    "Naveen",id:      565,address: "Coimbatore",salary:  90000,country: "India",}createQuery(e)i := 90createQuery(i)}//  insert into order values(456, 56)  //  insert into employee values("Naveen", 565, "Coimbatore", 90000, "India")  //  unsupported type  

二、 Reading Files

1. Reading Files 读取文件

        package mainimport ("fmt""os")func main() {contents, err := os.ReadFile("test.txt")if err != nil {fmt.Println("File reading error", err)return}fmt.Println("Contents os file:", string(contents))}// Contents os file: Hello World. Welcome to file handling in GO

2. Using absolute file path 使用绝对路径

        package mainimport ("fmt""os")func main() {contents, err := os.ReadFile("D:/Go/oop/test.txt")if err != nil {fmt.Println("File reading error", err)return}fmt.Println("Contents os file:", string(contents))}// Contents os file: Hello World. Welcome to file handling in GO

3. Passing the file path as a command line flag 将文件路径作为命令行标志传递

        package main  import (  "flag""fmt")func main() {  fptr := flag.String("fpath", "test.txt", "file path to read from")flag.Parse()contents, err := os.ReadFile(*fptr)if err != nil {fmt.Println("File reading error", err)return}fmt.Println("Contents of file: ", string(contents))}// Contents of file:  Hello World. Welcome to file handling in GO.

4. Reading a file in small chunks

        package mainimport ("bufio""flag""fmt""io""log""os")func main() {targetPath := flag.String("targetPath", "test.txt", "file path to read from")flag.Parse() // 进行命令行参数的解析 将相应的值赋给标志变量targetPathf, err := os.Open(*targetPath) // err: nil  f: *os.Fileif err != nil {log.Fatal(err) // 将错误信息打印到标准错误输出}defer func() { // 延迟开启匿名函数一直循环 如果关闭文件时发送错误 log处理错误if err = f.Close(); err != nil {log.Fatal(err)}}()r := bufio.NewReader(f) // 创建了一个 bufio.Reader 对象r用于逐行读取文件内容b := make([]byte, 3)for {n, err := r.Read(b) //  r.Read(b) 方法读取文件内容 将读取到的内容存储在字节切片b中 并返回读取的字节数n和可能出现的错误errif err == io.EOF {  // 如果读取到文件末尾输出fmt.Println("Finished reading file")break}if err != nil { // 如果读取文件发生错误fmt.Println("Error %s reading files", err)break}fmt.Println(string(b[0:n])) // 输出切片内容 切片容量3}}// Hel  // lo  // Wor  // ld.  //  We// lco  // me  // to  // fil  // e h  // and  // lin  // g i  // n G  // o.  // finished reading file  

5. Reading a file line by line 逐行读取文件

        package mainimport (  "bufio""flag""fmt""log""os")func main() {  fptr := flag.String("fpath", "test.txt", "file path to read from")flag.Parse()f, err := os.Open(*fptr)if err != nil {log.Fatal(err)}defer func() {if err = f.Close(); err != nil {log.Fatal(err)}}()s := bufio.NewScanner(f)for s.Scan() {fmt.Println(s.Text())}err = s.Err()if err != nil {log.Fatal(err)}}// Hello World. Welcome to file handling in Go.  // This is the second line of the file.  // We have reached the end of the file.  

相关文章:

Go语言高阶:Reflection反射与Files操作 详细示例教程

目录标题 一、Reflection反射1. What is reflection? 什么是反射2. Inspect a variable and find its type 检查变量并找到它的类型3. Reflect.Type and reflect.Value 反射类型和值4. Reflect.Kind 查看底层种类5. NumField() and Field() methods 字段数量和索引值方法6. In…...

谷歌seo技术流

很多外贸企业和独立站都想从Google获得免费的流量&#xff0c;也就是SEO流量&#xff0c;但是在做SEO的过程中&#xff0c;总会面临这样或那样的问题。米贸搜谷歌推广将这些问题总结如下&#xff1a; 既然SEO看起来似乎很难&#xff0c;但还是有很多电商公司愿意投资SEO&#x…...

ReactiveUI MVVM框架(1)-Collections

ReactiveUI MVVM框架&#xff08;1&#xff09;-Collections ReactiveUI使用动态数据&#xff08;DynamicData&#xff09;用于集合的操作。 当对动态数据集合进行更改时&#xff0c;会产生更改通知&#xff0c;通知表示为ChangeSet&#xff0c;里面包含了更改信息&#xff0…...

【微服务】五. Nacos服务注册

Nacos服务注册 5.1 Nacos服务分级存储模型Nacos服务分级存储模型&#xff1a;服务集群属性&#xff1a;总结&#xff1a; 5.2 根据集群负载均衡总结 5.3 Nacos服务实例的权重设置总结&#xff1a; 5.6 环境隔离namespace总结 5.7 Nacos和Eureka的对比总结 5.1 Nacos服务分级存储…...

Lnmp架构-Redis

网站&#xff1a;www.redis.cn redis 部署 make的时候需要gcc和make 如果在纯净的环境下需要执行此命令 [rootserver3 redis-6.2.4]# yum install make gcc -y 注释一下这几行 vim /etc/redis/6739.conf 2.Redis主从复制 设置 11 是master 12 13 是slave 在12 上 其他节…...

Python 二进制数据处理与转换

不得不说&#xff0c;Python能火是有原因的&#xff0c;物联网开发中常用的数据处理方式&#xff0c;Python都有内置的函数或方法&#xff0c;相当方便&#xff0c;官方文档见二进制序列类型&#xff0c;下面是一些示例代码 string Hello World! # 字符串转二进制数据 data …...

【LeetCode】297.二叉树的序列化与反序列化

题目 序列化是将一个数据结构或者对象转换为连续的比特位的操作&#xff0c;进而可以将转换后的数据存储在一个文件或者内存中&#xff0c;同时也可以通过网络传输到另一个计算机环境&#xff0c;采取相反方式重构得到原数据。 请设计一个算法来实现二叉树的序列化与反序列化…...

Java HashSet

HashSet 基于 HashMap 来实现的&#xff0c;是一个不允许有重复元素的集合。 HashSet 允许有 null 值。 HashSet 是无序的&#xff0c;即不会记录插入的顺序。 HashSet 不是线程安全的&#xff0c; 如果多个线程尝试同时修改 HashSet&#xff0c;则最终结果是不确定的。 您必…...

在iPhone上构建自定义数据采集完整指南

在iPhone上构建自定义数据采集工具可以帮助我们更好地满足特定需求&#xff0c;提高数据采集的灵活性和准确性。本文将为您提供一份完整的指南和示例代码&#xff0c;教您如何在iPhone上构建自定义数据采集工具。 自定义数据采集工具的核心组件 a、数据模型 数据模型是数据采…...

Android MediaRecorder录音

1. 简介 在android中录制音频有两种方式&#xff0c;MediaRecorder和AudioRecord。两者的区别如下&#xff1a; MediaRecorder 简单方便&#xff0c;不需要理会中间录制过程&#xff0c;结束录制后可以直接得到音频文件进行播放&#xff1b;录制的音频文件是经过压缩的&#…...

软件提示vcruntime140_1.dll丢失的解决方法,以及丢失的原因总结

在运行某些程序时&#xff0c;可能会出现“vcruntime140_1.dll 丢失”的错误提示。这是因为 vcruntime140_1.dll 是 Visual C Redistributable 的一部分&#xff0c;它通常被安装在 Windows 操作系统上。如果该文件丢失或无法找到&#xff0c;可能会导致程序无法正常运行。在我…...

Datax抽取mysql的bit类型数据

背景&#xff1a;使用datax抽取mysql的一张表&#xff0c;里面有两个bit类型的字段&#xff0c;抽取出来显示如下&#xff1a; 需要在抽取reader里面进行处理配置 最终生成的datax的json文件reader的配置会转换为具体的数值 最终查询效果&#xff1a;...

git 后悔药

前言 自上而下&#xff0c;撤销可以分为从远程库撤销&#xff0c;从本地库撤销&#xff0c;从暂存库撤销。 例子&#xff1a;代码已经提交了三个记录到远程库&#xff0c;分别对应了记录1&#xff0c;内容1&#xff0c;记录2&#xff0c;内容2&#xff0c;记录3&#xff0c;内…...

vue-cli搭建一个新项目及基础配置

vue-cli搭建一个新项目及基础配置 一、安装步骤二、main.js配置三、router下的index.js 一、安装步骤 1.安装node环境&#xff1a;下载地址&#xff1a;Node.js 2.安装脚手架&#xff1a;npm install -g vue/cli 3.创建vue项目&#xff1a;vue create 项目名 4.进入项目&…...

【C++】 C++11(右值引用,移动语义,bind,包装器,lambda,线程库)

文章目录 1. C11简介2. 统一的列表初始化2.1 &#xff5b;&#xff5d;初始化2.2 std::initializer_list 3. 声明3.1 auto3.2 decltype3.3 auto与decltype区别3.4 nullptr 4. 右值引用和移动语义4.1 左值引用和右值引用4.2 左值引用与右值引用比较4.3 右值引用使用场景和意义4.…...

附录1-爬虫的一些技巧

目录 1 寻找url与显示内容的关系 2 修改请求头 3 局部刷新 4 阅读返回信息 5 多尝试页面其他的使用方式 6 尝试不同类型参数 7 表单类型的post多用data发&#xff0c;接口类型的post多用json发 8 消除degger 9 你在浏览器上看到的html与你下载下来的html不一…...

【android12-linux-5.1】【ST芯片】【RK3588】【LSM6DSR】HAL移植

一、环境介绍 RK3588主板搭载Android12操作系统,内核是Linux5.10,使用ST的六轴传感器LSM6DSR芯片。 二、芯片介绍 LSM6DSR是一款加速度和角速度(陀螺仪)六轴传感器,还内置了一个温度传感器。该芯片可以选择I2C,SPI通讯,还有可编程终端,可以后置摄像头等设备,功能是很…...

DragGAN应运而生,未来在4G视频上都可能利用拖拽式编辑

原创 | 文 BFT机器人 2023年8月14日-15日&#xff0c;第七届GAIR全球人工智能与机器人大会在新加坡乌节大酒店成功举办。 在「AIGC 和生成式内容」分论坛上&#xff0c;南洋理工大学科学与工程学院助理教授潘新钢以《Interacitve Point-Dragging Manipulation of Visual Cont…...

【C++技能树】多态解析

Halo&#xff0c;这里是Ppeua。平时主要更新C&#xff0c;数据结构算法&#xff0c;Linux与ROS…感兴趣就关注我bua&#xff01; 文章目录 0.多态的概念0.1 多态的定义 1. 重写2.Final与Override3.抽象类4.多态中的内存分布.4.1虚表存在哪里? 5.多态调用原理5.1 动态绑定与静…...

【爬虫笔记】Python爬虫简单运用爬取代理IP

一、前言 近些年来&#xff0c;网络上的爬虫越来越多&#xff0c;很多网站都针对爬虫进行了限制&#xff0c;封禁了一些不规则的请求。为了实现正常的网络爬虫任务&#xff0c;爬虫常用代理IP来隐藏自己的真实IP&#xff0c;避免被服务器封禁。本文将介绍如何使用Python爬虫来…...

第19节 Node.js Express 框架

Express 是一个为Node.js设计的web开发框架&#xff0c;它基于nodejs平台。 Express 简介 Express是一个简洁而灵活的node.js Web应用框架, 提供了一系列强大特性帮助你创建各种Web应用&#xff0c;和丰富的HTTP工具。 使用Express可以快速地搭建一个完整功能的网站。 Expre…...

【网络】每天掌握一个Linux命令 - iftop

在Linux系统中&#xff0c;iftop是网络管理的得力助手&#xff0c;能实时监控网络流量、连接情况等&#xff0c;帮助排查网络异常。接下来从多方面详细介绍它。 目录 【网络】每天掌握一个Linux命令 - iftop工具概述安装方式核心功能基础用法进阶操作实战案例面试题场景生产场景…...

Debian系统简介

目录 Debian系统介绍 Debian版本介绍 Debian软件源介绍 软件包管理工具dpkg dpkg核心指令详解 安装软件包 卸载软件包 查询软件包状态 验证软件包完整性 手动处理依赖关系 dpkg vs apt Debian系统介绍 Debian 和 Ubuntu 都是基于 Debian内核 的 Linux 发行版&#xff…...

LeetCode - 394. 字符串解码

题目 394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; 思路 使用两个栈&#xff1a;一个存储重复次数&#xff0c;一个存储字符串 遍历输入字符串&#xff1a; 数字处理&#xff1a;遇到数字时&#xff0c;累积计算重复次数左括号处理&#xff1a;保存当前状态&a…...

STM32标准库-DMA直接存储器存取

文章目录 一、DMA1.1简介1.2存储器映像1.3DMA框图1.4DMA基本结构1.5DMA请求1.6数据宽度与对齐1.7数据转运DMA1.8ADC扫描模式DMA 二、数据转运DMA2.1接线图2.2代码2.3相关API 一、DMA 1.1简介 DMA&#xff08;Direct Memory Access&#xff09;直接存储器存取 DMA可以提供外设…...

页面渲染流程与性能优化

页面渲染流程与性能优化详解&#xff08;完整版&#xff09; 一、现代浏览器渲染流程&#xff08;详细说明&#xff09; 1. 构建DOM树 浏览器接收到HTML文档后&#xff0c;会逐步解析并构建DOM&#xff08;Document Object Model&#xff09;树。具体过程如下&#xff1a; (…...

数据库分批入库

今天在工作中&#xff0c;遇到一个问题&#xff0c;就是分批查询的时候&#xff0c;由于批次过大导致出现了一些问题&#xff0c;一下是问题描述和解决方案&#xff1a; 示例&#xff1a; // 假设已有数据列表 dataList 和 PreparedStatement pstmt int batchSize 1000; // …...

【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具

第2章 虚拟机性能监控&#xff0c;故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令&#xff1a;jps [options] [hostid] 功能&#xff1a;本地虚拟机进程显示进程ID&#xff08;与ps相同&#xff09;&#xff0c;可同时显示主类&#x…...

初探Service服务发现机制

1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能&#xff1a;服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源&#xf…...

LLMs 系列实操科普(1)

写在前面&#xff1a; 本期内容我们继续 Andrej Karpathy 的《How I use LLMs》讲座内容&#xff0c;原视频时长 ~130 分钟&#xff0c;以实操演示主流的一些 LLMs 的使用&#xff0c;由于涉及到实操&#xff0c;实际上并不适合以文字整理&#xff0c;但还是决定尽量整理一份笔…...