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

KubeSphere 容器平台高可用:环境搭建与可视化操作指南

Linux_k8s篇 欢迎来到Linux的世界&#xff0c;看笔记好好学多敲多打&#xff0c;每个人都是大神&#xff01; 题目&#xff1a;KubeSphere 容器平台高可用&#xff1a;环境搭建与可视化操作指南 版本号: 1.0,0 作者: 老王要学习 日期: 2025.06.05 适用环境: Ubuntu22 文档说…...

基于算法竞赛的c++编程(28)结构体的进阶应用

结构体的嵌套与复杂数据组织 在C中&#xff0c;结构体可以嵌套使用&#xff0c;形成更复杂的数据结构。例如&#xff0c;可以通过嵌套结构体描述多层级数据关系&#xff1a; struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...

【网络安全产品大调研系列】2. 体验漏洞扫描

前言 2023 年漏洞扫描服务市场规模预计为 3.06&#xff08;十亿美元&#xff09;。漏洞扫描服务市场行业预计将从 2024 年的 3.48&#xff08;十亿美元&#xff09;增长到 2032 年的 9.54&#xff08;十亿美元&#xff09;。预测期内漏洞扫描服务市场 CAGR&#xff08;增长率&…...

高频面试之3Zookeeper

高频面试之3Zookeeper 文章目录 高频面试之3Zookeeper3.1 常用命令3.2 选举机制3.3 Zookeeper符合法则中哪两个&#xff1f;3.4 Zookeeper脑裂3.5 Zookeeper用来干嘛了 3.1 常用命令 ls、get、create、delete、deleteall3.2 选举机制 半数机制&#xff08;过半机制&#xff0…...

系统设计 --- MongoDB亿级数据查询优化策略

系统设计 --- MongoDB亿级数据查询分表策略 背景Solution --- 分表 背景 使用audit log实现Audi Trail功能 Audit Trail范围: 六个月数据量: 每秒5-7条audi log&#xff0c;共计7千万 – 1亿条数据需要实现全文检索按照时间倒序因为license问题&#xff0c;不能使用ELK只能使用…...

Python实现prophet 理论及参数优化

文章目录 Prophet理论及模型参数介绍Python代码完整实现prophet 添加外部数据进行模型优化 之前初步学习prophet的时候&#xff0c;写过一篇简单实现&#xff0c;后期随着对该模型的深入研究&#xff0c;本次记录涉及到prophet 的公式以及参数调优&#xff0c;从公式可以更直观…...

linux 下常用变更-8

1、删除普通用户 查询用户初始UID和GIDls -l /home/ ###家目录中查看UID cat /etc/group ###此文件查看GID删除用户1.编辑文件 /etc/passwd 找到对应的行&#xff0c;YW343:x:0:0::/home/YW343:/bin/bash 2.将标红的位置修改为用户对应初始UID和GID&#xff1a; YW3…...

【HTML-16】深入理解HTML中的块元素与行内元素

HTML元素根据其显示特性可以分为两大类&#xff1a;块元素(Block-level Elements)和行内元素(Inline Elements)。理解这两者的区别对于构建良好的网页布局至关重要。本文将全面解析这两种元素的特性、区别以及实际应用场景。 1. 块元素(Block-level Elements) 1.1 基本特性 …...

关于 WASM:1. WASM 基础原理

一、WASM 简介 1.1 WebAssembly 是什么&#xff1f; WebAssembly&#xff08;WASM&#xff09; 是一种能在现代浏览器中高效运行的二进制指令格式&#xff0c;它不是传统的编程语言&#xff0c;而是一种 低级字节码格式&#xff0c;可由高级语言&#xff08;如 C、C、Rust&am…...

学习STC51单片机32(芯片为STC89C52RCRC)OLED显示屏2

每日一言 今天的每一份坚持&#xff0c;都是在为未来积攒底气。 案例&#xff1a;OLED显示一个A 这边观察到一个点&#xff0c;怎么雪花了就是都是乱七八糟的占满了屏幕。。 解释 &#xff1a; 如果代码里信号切换太快&#xff08;比如 SDA 刚变&#xff0c;SCL 立刻变&#…...