当前位置:网站首页>Go language learning tutorial (14)
Go language learning tutorial (14)
2022-06-28 04:17:00 【Young Chen Gong】
One 、 Reflection introduction
* stay Go In the language standard library reflect Packages provide runtime reflection , Dynamic operation structure during program running
* When the variable stores the structure attribute name , When you want to assign or view this property of the structure , You can use reflection .
* Reflection can also be used to determine the type of variable
* Whole reflect The two most important types of packages
* reflect.Type type
* reflect.Value value
* Get Type and Value Function of
* reflect.TypeOf(interface{}) return Type
* reflect.ValueOf(interface{}) Return value Value
* Determine the type of variable
a:=1.5
fmt.Println(reflect.TypeOf(a))
* Get the value of the structure property
ype People struct {
Id int
Name string
}
func main() {
peo := People{1, " Zhang San "}
// obtain peo Value
v := reflect.ValueOf(peo)
// Get the number of attributes , If v Not a structure type panic
fmt.Println(v.NumField())
// For the first 0 Attributes ,id, And converted to int64 type
fmt.Println(v.Field(0).Int())
// For the first 1 Attributes , Convert to string type
fmt.Println(v.Field(1).String())
// Get type by name , And convert the type name to string type
idValue := v.FieldByName("Id")
fmt.Println(idValue.Kind().String())
}
* When setting the value of a structure property, a structure pointer is passed , No, you cannot get the set structure object
* When reflecting direct structural properties , It is required that the initial letter of the property name must be capitalized , Otherwise... Cannot be set
package main
import (
"fmt"
"reflect"
)
type People struct {
Id int
Name string
}
func main() {
peo := People{1, " Zhang San "}
/*
Get when reflecting peo The address of .
Elem() Gets the encapsulation where the pointer points to the address .
The value of the address must call Elem() Before you can continue to operate
*/
v := reflect.ValueOf(&peo).Elem()
fmt.Println(v.FieldByName("Id").CanSet())
v.FieldByName("Id").SetInt(123)
v.FieldByName("Name").SetString(" Li Si ")
fmt.Println(peo)
}
Two 、XML File info
* English full name :Extensible Markup Language
* Chinese full name : Extensible markup language
* purpose :
* data storage
* Data interaction
* The configuration file
* advantage :
* Cross-platform sex
* Neat data , Easy to read
* XML Document structure
* first line :XML head , Version and code
* The second line :DTD Optional , Be able to check XML Whether the content meets the requirements
* The outermost label <peoples> Called element nodes , The root node
* <people>...<people> The entire tag is called the element node
* id=”1” Attribute node
* Text in label : Text node
* Grammar requires
* Case sensitive
* Labels must be nested correctly , Must be closed correctly
* There must be a root node
* Attribute values must have double quotes
* notes :<!-- -->
* Special characters appear in the text node , You need to replace... With an entity reference
3、 ... and 、XML File content reading
* Go Language standard library provides API
* stay encoding/xml The package provides a pair of XML Serialized and deserialized API
* Use Unmarshal You can directly XML Byte slice data is converted to structure
* When converting, the conversion is carried out according to the specific conversion rules , And the data type can be automatically converted
* Code example
* Given XML The contents of the document are as follows
<?xml version="1.0" encoding="UTF-8" ?>
<people id="888">
<name>smallming</name>
<address> Beijing haidian </address>
</people>
* New structure , load XML data
* The attribute initial in the structure must be capitalized , Otherwise it can't be assembled
type People struct {
XMLName xml.Name `xml:"people"`
Id int `xml:"id,attr"`
Name string `xml:"name"`
Address string `xml:"address"`
}
func main() {
peo := new(People)
b, err := ioutil.ReadFile("demo.xml")
fmt.Println(string(b))
fmt.Println("111:", err)
err = xml.Unmarshal(b, peo)
fmt.Println("2222", err)
fmt.Println(peo)
}
Four 、XML File generation
* Generate XML need encoding/xml Under bag Marshal() function , Combined with the input stream xml File generation
* stay encoding/xml Constant in , In the constant is xml Document header
* Use Marshal() Function generated []byte No formatting
* Use MarshalIndent() You can format the content
* The first parameter : Structure object
* The second parameter : Prefix of each line
* The third parameter : Level indent content
type People struct {
XMLName xml.Name `xml:"people"`
Id int `xml:"id,attr"`
Name string `xml:"name"`
Address string `xml:"address"`
}
func main() {
peo := People{Id: 123, Name: "smallming", Address: " Beijing haidian "}
b, _ := xml.MarshalIndent(peo, "", " ")
b = append([]byte(xml.Header), b...)
ioutil.WriteFile("D:/peo.xml", b, 0666)
fmt.Println(" Program end ")
}
5、 ... and 、 Introduction to the log
* When using development tools , The information printed on the console is the log information
* There is no development tool after the project is finally released . If you need to log, you should output the information to a file , This function is also a log function
* stay Go Language standard log Support for logging is provided in the package
* There are three levels of log output
* Print() Output log information
* Panic() Print log information , And trigger panic, The log information is Panic Information
* Fatal() Call after printing the log information os.Exit(1)
* All log information is printed with time , And the color is red
* Each level of log printing provides three functions
* Println()
* Print()
* Printf()
* The log file extension is log
6、 ... and 、 Normal log information printing
* Use it directly log Package call Println() that will do
log.Println(" Print log information ")
7、 ... and 、Panic Log information printing
* Output log information after execution , It also triggers panic
log.Panicln(" Print log information ")
8、 ... and 、 Fatal log information
* After executing log printing , The program was terminated
log.Fatal(" Print log information ")
Nine 、 Print log information to a file
* Go The language standard library supports outputting log information to files .
f, _ := os.OpenFile("D:/golog.log", os.O_APPEND|os.O_CREATE, 07777)
defer f.Close()
logger := log.New(f, "[info]\t", log.Ltime)
logger.Println(" Output log information ")
边栏推荐
- Introduction to multi project development, basic design class library project use
- Uncover the mystery of SSL and learn how to protect data with SSL
- 用一个栈实现另一个栈的排序
- 光伏板怎么申请ASTM E108阻燃测试?
- Elk builds log analysis system + Zipkin service link tracking integration
- JVM I: introduction to JVM and understanding of class files
- 公司领导说,个人代码超10个Bug就开除,是什么体验?
- 04 MongoDB各种查询操作 以及聚合操作总结
- Reverse a stack with recursive functions and stack operations only
- Go language -select statement
猜你喜欢
Visualization of loss using tensorboard
从零到一,教你搭建「以文搜图」搜索服务(一)
《性能之巅第2版》阅读笔记(二)--CPU监测
如何遍历collections.OrderedDict,服了又忘记items
2021年终总结及2022年展望
02 MongoDB数据类型、重要概念以及shell常用指令
歐洲家具EN 597-1 跟EN 597-2兩個阻燃標准一樣嗎?
公司领导说,个人代码超10个Bug就开除,是什么体验?
leetcode - 329. Longest increasing path in matrix
MSC 307(88) (2010 FTPC Code)第2部分烟气和毒性测试
随机推荐
利用ELK 搭建日志分析系统(一)—— 组件介绍
MSc 307 (88) (2010 FTPC code) Part 2 smoke and toxicity test
CDC全量抽取mysql数据时,怎么才能加快ChunkSplitter呢?
Go语言学习教程(十四)
成长一夏 挑战赛来袭 | 学习、创作两大赛道,开启导师报名啦!
2021年终总结及2022年展望
Reading notes of top performance version 2 (II) -- CPU monitoring
2022年中国音频市场年度综合分析
Introversion, lying flat and midlife crisis
ELK 搭建日志分析系统 + Zipkin服务链路追踪整合
等保2.0密码要求是什么?法律依据有哪些?
RT-Thread 双向链表(学习笔记)
Introduction to SQLSERVER database
美创入选“2022 CCIA中国网络安全竞争力50强”榜单
How to write a software test report? Here comes the third party performance report template
01 overview, application scenarios, Download methods, connection methods and development history of mongodb
从零到一,教你搭建「以文搜图」搜索服务(一)
品达通用权限系统(Day 5~Day 6)
Building log analysis system with elk (III) -- Security Authentication
【MySQL】多表连接查询