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

Qwen3-TTS作品分享:听AI朗读你的日记、诗歌和故事

Qwen3-TTS作品分享&#xff1a;听AI朗读你的日记、诗歌和故事 1. 为什么你需要一个会"读心"的语音合成工具 想象一下这样的场景&#xff1a;深夜写完日记&#xff0c;点击播放键&#xff0c;听到一个温暖的声音将你的文字娓娓道来&#xff1b;创作完一首诗&#xf…...

MusePublic Art Studio效果展示:复杂提示词(多主体/空间关系/光照条件)解析能力

MusePublic Art Studio效果展示&#xff1a;复杂提示词&#xff08;多主体/空间关系/光照条件&#xff09;解析能力 1. 创作工具新体验 MusePublic Art Studio让AI图像生成变得像使用画笔一样简单。这个工具专门为创作者设计&#xff0c;不需要懂任何代码技术&#xff0c;通过…...

鸿蒙与Android双端蓝牙开发避坑指南:定位权限、虚拟地址与厂商SDK那些事

鸿蒙与Android双端蓝牙开发实战&#xff1a;权限策略与真实地址获取全解析 当你的应用需要同时在鸿蒙和Android设备上稳定运行蓝牙功能时&#xff0c;系统差异就像一片雷区——Android 12的权限拆分、鸿蒙4.0的虚拟地址返回、不同版本间的API兼容性&#xff0c;每个环节都可能让…...

【花雕学编程】Arduino BLDC 之使用互补滤波进行姿态控制的机器人

从专业工程视角来看&#xff0c;基于Arduino、使用互补滤波进行姿态控制的BLDC&#xff08;无刷直流电机&#xff09;机器人&#xff0c;是一个典型的嵌入式实时闭环控制系统。它集成了传感器数据融合、控制算法和电机驱动&#xff0c;广泛应用于对姿态稳定性有要求的场景。 1、…...

Display Driver Uninstaller(DDU):显卡驱动深度清理工具,解决游戏玩家与设计师的驱动残留难题

Display Driver Uninstaller&#xff08;DDU&#xff09;&#xff1a;显卡驱动深度清理工具&#xff0c;解决游戏玩家与设计师的驱动残留难题 【免费下载链接】display-drivers-uninstaller Display Driver Uninstaller (DDU) a driver removal utility / cleaner utility 项…...

告别OpenAI API费用:手把手教你用本地BGE模型+FAISS搭建LangChain私有知识库

零成本构建企业级知识库&#xff1a;基于BGE与FAISS的私有化LangChain解决方案 在AI应用开发领域&#xff0c;数据隐私和成本控制正成为越来越多开发者的核心考量。当OpenAI等商业API按调用次数收费时&#xff0c;频繁的查询请求可能让个人开发者和小型团队不堪重负。更关键的是…...

WebLogic T3协议漏洞实战:5分钟搞定ConnectionFilterImpl配置(附常见问题排查)

WebLogic T3协议安全加固实战&#xff1a;ConnectionFilterImpl配置与深度防御指南 1. 漏洞背景与防御必要性 WebLogic作为企业级Java应用服务器&#xff0c;其专有的T3协议长期存在反序列化漏洞风险。攻击者通过构造恶意T3协议数据包&#xff0c;可在未授权情况下实现远程代码…...

300 元内降噪耳机横评:倍思 M2s / 绿联 T3 / 漫步者 X5 Pro 实测对比(续航・降噪・延迟全数据)

300 元内降噪耳机横评&#xff1a;倍思 M2s / 绿联 T3 / 漫步者 X5 Pro 实测数据对比&#xff08;附续航 / 降噪 / 延迟测试结果&#xff09; 摘要 本文针对学生党、通勤族高频使用的 300 元内主动降噪耳机&#xff0c;选取倍思 M2s、绿联 HiTune T3、漫步者 X5 Pro 三款热门机…...

构建实时体积渲染管线:Unreal VDB插件深度解析与实践指南

构建实时体积渲染管线&#xff1a;Unreal VDB插件深度解析与实践指南 【免费下载链接】unreal-vdb This repo is a non-official Unreal plugin that can read OpenVDB and NanoVDB files in Unreal. 项目地址: https://gitcode.com/gh_mirrors/un/unreal-vdb 在实时渲染…...

概率预测实战 —— DeepAR 模型在电力负荷预测中的应用

1. 为什么电力行业需要概率预测&#xff1f; 想象一下你正在规划下周的家庭用电。如果只知道"大概会用100度电"&#xff0c;和知道"90%概率在95-105度之间"&#xff0c;哪种信息更有价值&#xff1f;这就是电力负荷预测从点预测升级到概率预测的核心价值。…...