当前位置:网站首页>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"
原网站

版权声明
本文为[It's haohaozi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091813238759.html