当前位置: 首页 > 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爬虫来…...

BouncyCastle.NET证书管理完全教程:生成、验证与撤销的终极指南 [特殊字符]

BouncyCastle.NET证书管理完全教程&#xff1a;生成、验证与撤销的终极指南 &#x1f510; 【免费下载链接】bc-csharp BouncyCastle.NET Cryptography Library (Mirror) 项目地址: https://gitcode.com/gh_mirrors/bc/bc-csharp 在当今数字安全至关重要的时代&#xff…...

ngx_http_read_request_header

1 定义 ngx_http_read_request_header 函数 定义在 ./nginx-1.24.0/src/http/ngx_http_request.cstatic ssize_t ngx_http_read_request_header(ngx_http_request_t *r) {ssize_t n;ngx_event_t *rev;ngx_connection_t *c;ngx_http_…...

终极指南:如何安全高效地使用APKMirror下载安卓应用

终极指南&#xff1a;如何安全高效地使用APKMirror下载安卓应用 【免费下载链接】APKMirror 项目地址: https://gitcode.com/gh_mirrors/ap/APKMirror APKMirror是一款专注于安卓应用安全下载与管理的开源工具&#xff0c;为你提供官方应用商店之外的可靠替代方案。通过…...

AI编程提示工程实战:从AwesomeCursorPrompt看高效开发与社区协作

1. 项目概述&#xff1a;从“Awesome”前缀看提示工程的社区实践在AI应用开发&#xff0c;特别是大语言模型&#xff08;LLM&#xff09;和AI助手交互的领域&#xff0c;一个清晰、结构化的提示&#xff08;Prompt&#xff09;往往决定了最终输出质量的80%。很多开发者都有过这…...

【ElevenLabs情绪语音实战指南】:3步解锁开心语音API调用、情感强度微调与合规避坑全链路

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;ElevenLabs开心情绪语音技术全景概览 核心技术能力 ElevenLabs 的开心情绪语音生成并非简单音调拉升或语速加快&#xff0c;而是基于多任务情感条件建模&#xff08;Multi-Task Emotional Conditionin…...

抖音弹幕抓取神器:5分钟快速上手与深度应用指南

抖音弹幕抓取神器&#xff1a;5分钟快速上手与深度应用指南 【免费下载链接】DouyinBarrageGrab 基于系统代理的抖音弹幕wss抓取程序&#xff0c;能够获取所有数据来源&#xff0c;包括chrome&#xff0c;抖音直播伴侣等&#xff0c;可进行进程过滤 项目地址: https://gitcod…...

8B模型做生物实验:实验步骤顺序不乱、剂量无幻觉|ICLR 2026

Thoth团队 投稿量子位 | 公众号 QbitAI人类研究员做实验&#xff0c;从来不是把几句步骤随手拼起来。一份真正可复现的实验protocol&#xff0c;需要明确每一步做什么、对什么对象操作、用什么参数&#xff0c;以及步骤之间的先后依赖。一旦顺序错了、剂量错了、对象错了&#…...

LabVIEW架构演进:从数据流到混合计算与云原生的未来

1. 项目概述&#xff1a;从一次访谈看LabVIEW的架构演进最近&#xff0c;我偶然看到一篇关于LabVIEW之父Jeff Kodosky的访谈&#xff0c;他谈到了LabVIEW未来软件架构的构想。作为一名在测控领域摸爬滚打了十多年的工程师&#xff0c;这个话题瞬间就抓住了我的眼球。LabVIEW&am…...

2026年网络安全行业发展全景解析(技术从业者必看)_最新网络行业发展锐评

2026年网络安全行业发展全景解析&#xff08;技术从业者必看&#xff09; 摘要&#xff1a;随着数字化转型进入深水区&#xff0c;AI、云原生、物联网等技术的普及&#xff0c;网络安全已从“辅助保障”升级为“核心刚需”。 一、行业发展现状&#xff1a;政策与市场双轮驱动&…...

BepInEx插件框架:为什么它是Unity游戏Mod开发的终极解决方案?

BepInEx插件框架&#xff1a;为什么它是Unity游戏Mod开发的终极解决方案&#xff1f; 【免费下载链接】BepInEx Unity / XNA game patcher and plugin framework 项目地址: https://gitcode.com/GitHub_Trending/be/BepInEx 你是否曾经想过为喜欢的Unity游戏添加新功能&…...