当前位置:网站首页>Golang Foundation (4)
Golang Foundation (4)
2022-06-09 18:17:00 【It's haohaozi】
7、 ... and 、 Data labels : mapping
Go There is another way to save data sets : mapping . A map is a collection of values that are accessed through keys . Keys are a simple way to find data from a map . Like a neatly marked folder , Instead of a messy stack . To declare a variable that holds the mapping , Please enter a map keyword , Followed by a pair of square brackets containing the key type ([]). Then provide the type of the value after the square brackets .
// string Is the key type ,float64 Value type
var myMap map[string]float64
// Declare a mapping variable
var ranks map[string]int
// Really create a map
ranks=make(map[string]int)
// More convenient way
ranks:=make(map[string]int)
Arrays and slices only allow you to use integers as indexes . And you can use almost any type as a mapping key .
elements:=make(map[string] string)
elements["H"]="Hydrogen"
elements["Li"]="Lithium"
fmt.Println(elements["Li"]) // Lithium
fmt. Println(elements["H"]) // Hydrogen
Mapping literal
Map literals to map types ( With “ mapping [ Key type ] Value type ” In the form of ) Start . Followed by curly braces , Contains the keys that you want to map initially / It's worth it . For each key / It's worth it , Contains a key 、 A colon and a value . Multiple keys / Value pairs are separated by commas .
ranks:=map[string]int{
"bronze":3,"silver":2,"gold":1}
fmt,Println(ranks["gold"]) // 1
fmt.Println(ranks["bronze"]) //3
elements:=map[string]string {
// Multiline mapping literal
"H":"Hydrogen",
"Li":"Lithium",
}
fmt.Println(elements["H"]) // Hydrogen
fnt.Println(elements["Li"]) // Lithium
Distinguish between assigned values and zero values
When accessing the mapping key, you can optionally get the number 2 Boolean values . If this key has been assigned a value , Then the return true, Otherwise return to false. majority Go The developer will assign this Boolean value to a named ok The variable of ( Because the name is short and effective ).
data:=[] string("a","c","e","a","e")
counts:=make(map[string] int)
for _, item:=range data{
counts[item]++
}
letters:=[]string{
"a","b","c","d","e"}
for _, letter:=range letters{
count, ok:=counts[letter]
if !ok{
fmt. Printf("%s: not found\n", letter)
} else {
fmt. Printf("%s: %d\n", letter, count)
}
}
Use “delete” Function delete key / It's worth it
utilize delete Function to delete the assigned value from the map . Just pass it on to delete Two parameters : You want to delete the mapping of the data and the keys you want to delete . Then the key and its associated values are deleted .
ranks:=make(map[string]int)
ranks["bronze"]=3
delete(ranks,"bronze")
isPrime:=make(map[int]bool)
isPrime[5]=true
delete(isPrime,5)
Mapping for…range loop
With arrays and slices for…range Cycle comparison . Unlike assigning an integer index to the first variable , The mapping assigns the key to the first variable .
package main
import (
"fmt"
"sort"
)
func main() {
grade:=map[string]float64{
"Alma":74.2,"Rohit":86.5,"Carl":59.7}
var names []string
for name := range grades {
// Key values ignored here , But no “_”
names:=append(names,name)
}
sort.String(names)
for_,name:=range names {
fmt.Printf("%s has a grade of %0.1f%%\n",name,grade[name])
}
}
Open ballot statistical procedures
package main
import(
"fmt"
"github. com/headfirstgo/datafile"
"1og"
}
func main() {
lines, err:=datafile. GetStrings("votes. txt")
if err!=nil{
log. Fatal(err)
}
counts:=make(map[string] int)
for _, line:=range lines{
counts[line]++
}
for name,count:=range counts {
fmt.Printf("Votes for %s: %d\n",name,count)
}
}
8、 ... and 、 Build storage :struct
Sometimes you need to save more than one type of data . We learned slicing , It can save a set of data . Then I learned mapping , It can hold a set of keys and a set of values . Both data structures can hold only one type . Sometimes , You need a set of different types of data , E.g. email address , Mixed street names ( String type ) And postal code ( integer ); Another example is student records , Mix and save student names and grades ( Floating point numbers ). You can't save with slices or maps . But you can use other names struct Type to save .
var myStruct struct {
field1 string
field2 int
number float64
}
// Use the dot operator to identify those belonging to struct Field of . This can also be used to assign and retrieve them
myStruct.number=3.14
Define the type and struct
Type definitions allow you to create new types yourself . You can create new definition types based on the base types .
To define a type , Need to use type keyword , Followed by the name of the new type , Then there's the base type you want to be based on . If you use struct Type as your base type , You need to use struct keyword , Followed by a set of field definitions wrapped in curly braces , Just like you declared struct Variables, as they do .
type myType struct {
// fields here
}
It's like variables , Can be placed in a function type . But limit its scope to this function block , It means you can't use it outside the function . So types are often defined at the package level outside the function .
package main
import "fmt"
type part struct {
description string
count int
}
func minimumOrder(description string) part {
var p part
p.description=description
p.count=100
return p // return part
}
func main() {
p:=minimumOrder("Hex bolts")
fmt.Println(p.description,p.count) // Hex bolts 100
}
Be careful : If you have defined a package named car The type of , And you also have a declaration called car The variable of , This variable will mask the type name , Make the latter inaccessible .
Access by pointer struct Field of
(*pointer).myField Soon it will be boring . therefore , The dot operator allows you to pass through strcut To access fields , Just like you can pass struct Value direct access .
var value myStruct
value.myField=3
var pointer *myStruct=&value
fmt.Println((*pointer).myField) // 3,*pointer.myField It's wrong.
fmt.Println(pointer.myField)
Function parameters receive a copy of the arguments of a function call , Even if it's struct So it is with . If you pass a large... With many fields struct, That would take up a lot of computer memory .
Even if one struct Types are exported from packages , If its field name is not capitalized , Its fields will not be exported .
type Part struct {
Description string // Field names are capitalized
count int
}
struct Literal
This syntax looks very similar to mapping . The type is listed first , Followed by a pair of curly braces . Inside the curly braces , You can give some or all struct Field assignment . Use the field name : Format of value . If you define multiple fields , Separated by commas .
package magazine
type Subscriber struct {
Name string
Rate float64
Active bool
}
import managine
// We have to deal with struct Variables use long declarations ( Unless struct Is returned from a function ).struct Literals allow us to evaluate the newly created struct Declare with short variables .
subscriber:=manazine.Subscriber{
Name:"Aman Singh",Rate:4.99,Active:true}
// Structure can also contain structure fields
subscriber.HomeAddress.PostalCode="68111"
anonymous struct Field
type Employee struct {
Name string
Salary float64
HomeAddress Address
}
type Address struct {
Street string
PostalCode int
}
// Go Allows you to define an anonymous field :struct Field has no name , There are only types .
// We can use anonymous fields to make internal struct Access is simpler
type Employee struct {
Name string
Salary string
Address // Anonymous field
}
// visit
employee:=manazine.Employee{
Name:"Joy Carr"}
emploee.Address.PostalCode="97222"
// More concise access
emploee.PostalCode="97222"
边栏推荐
- 入驻快讯|欢迎XCHARGE智充科技正式入驻 InfoQ 写作平台!
- synchronized实现原理和锁升级过程
- 如何利用无线通讯技术优化钢铁厂消防用水管网?
- Overview of GCN graph convolution neural network
- 【高等数学笔记】格林公式、高斯公式、斯托克斯公式、场论
- redis源码学习-03_动态字符串SDS
- Synchronized implementation principle and lock upgrade process
- 10 common high-frequency business scenarios that trigger IO bottlenecks
- crontab定时执行任务
- 【玩转华为云】华为云零代码开发图片压缩工具
猜你喜欢

功能:多文件上传,统一提交

【工作随笔记】Tina 系统的 ADB、声卡、网卡、串口多路共存

155_ Model_ Safety stock of power Bi & power pivot purchase, sales and inventory

JsonPath-教程

GCN图卷积神经网络概述

Overview of GCN graph convolution neural network

Redis knowledge points & summary of interview questions

155_模型_Power BI & Power Pivot 进销存之安全库存

进程控制--->进程终止

AI首席架构师3-AICA-智慧城市中的AI应用实践
随机推荐
ElasticSerach
Redis基础与高级
Overview of GCN graph convolution neural network
Introduction to Multivariate Statistics
Epigentek chromatin accessibility test kit principles and procedures
DM8查看SQL执行计划的5种方法(测试+调优用)
Interpretation of new shares | ranked second in the event content marketing industry, and wanted to push SaaS products on the cloud to create a competitive barrier
10 common high-frequency business scenarios that trigger IO bottlenecks
Synchronized implementation principle and lock upgrade process
Go 最细节篇|pprof 统计的内存总是偏小?
深度学习与CV教程(10) | 轻量化CNN架构 (SqueezeNet,ShuffleNet,MobileNet等)
贤弟单腾,因崔思婷,机器人类打字~~~~~~
【数据处理】pandas读取sql数据
如何实现工厂生产能耗数据的无线监测?
Process control -- > > process termination
CORTEX-A9三星iTOP-4412开发开发板入门嵌入式
Redis知识点&面试题总结
深入理解联合索引的最左前缀原则
微信小程序根据经纬度获取省市区信息
kubectl 最新常用命令 --V1.24版本