- Go Systems Programming
- Mihalis Tsoukalos
- 352字
- 2021-07-02 18:08:00
Structures
Although arrays, slices, and maps are all very useful, they cannot hold multiple values in the same place. When you need to group various types of variables and create a new handy type, you can use a structure--the various elements of a structure are called fields.
The code of this subsection is saved as dataStructures.go and can be divided into three parts. The first part contains the preamble and the definition of a new structure named message:
package main import ( "fmt" "reflect" ) func main() { type message struct { X int Y int Label string }
The message structure has three fields, named X, Y, and Label. Note that structures are usually defined at the beginning of a program and outside the main() function.
The second part uses the message structure to define two new message variables, named p1 and p2. Then, it uses reflection to get information about the p1 and p2 variables of the message structure:
p1 := message{23, 12, "A Message"} p2 := message{} p2.Label = "Message 2" s1 := reflect.ValueOf(&p1).Elem() s2 := reflect.ValueOf(&p2).Elem() fmt.Println("S2= ", s2)
The last part shows how to print all the fields of a structure without knowing their names using a for loop and the Type() function:
typeOfT := s1.Type() fmt.Println("P1=", p1) fmt.Println("P2=", p2) for i := 0; i < s1.NumField(); i++ {
f := s1.Field(i)
fmt.Printf("%d: %s ", i, typeOfT.Field(i).Name) fmt.Printf("%s = %v\n", f.Type(), f.Interface()) } }
Running dataStructures.go will generate the following kind of output:
$ go run dataStructures.go S2= {0 0 Message 2} P1= {23 12 A Message} P2= {0 0 Message 2} 0: X int = 23 1: Y int = 12 2: Label string = A Message
If the name of a field of a struct definition begins with a lowercase letter (x instead of X), the previous program will fail with the following error message:
panic: reflect.Value.Interface: cannot return value obtained from unexported field or method
This happens because lowercase fields do not get exported; therefore, they cannot be used by the reflect.Value.Interface() method. You will learn more about reflection in the next chapter.
- Expert C++
- Google Flutter Mobile Development Quick Start Guide
- Node.js 10實(shí)戰(zhàn)
- JavaScript+DHTML語法與范例詳解詞典
- 摩登創(chuàng)客:與智能手機(jī)和平板電腦共舞
- Arduino開發(fā)實(shí)戰(zhàn)指南:LabVIEW卷
- iOS開發(fā)實(shí)戰(zhàn):從零基礎(chǔ)到App Store上架
- Data Analysis with IBM SPSS Statistics
- 面向?qū)ο蟪绦蛟O(shè)計(jì)(Java版)
- STM32F0實(shí)戰(zhàn):基于HAL庫開發(fā)
- Big Data Analytics
- Extending Puppet(Second Edition)
- 零基礎(chǔ)Java學(xué)習(xí)筆記
- 微服務(wù)架構(gòu)深度解析:原理、實(shí)踐與進(jìn)階
- JavaScript程序設(shè)計(jì):基礎(chǔ)·PHP·XML