当前位置:网站首页>Go language | 02 for loop and the use of common functions
Go language | 02 for loop and the use of common functions
2022-07-05 19:51:00 【"Lose a shoe"】
List of articles
Preface
This thought Go Language and C Language similarity is high , But in for In the cycle of learning , I still feel a lot different , So make a study record
for & range function
for grammar
Go Linguistic For Circulatory 3 In the form of , Only one of them uses semicolons .
and C Linguistic for equally :
for init; condition; post {
}
and C Of while equally :
for condition {
}
and C Of for(; equally :
for {
}
- init: It's usually an assignment expression , Assign initial values to control variables ;
- condition: A relational or logical expression , Cycle control conditions ;
- post: It's usually an assignment expression , Increment or decrement of a control variable .
range I was in C Not much used in language development
for Use
Go In language range Keywords are used for for Iterating arrays in a loop (array)、 section (slice)、 passageway (channel) Or set (map) The elements of . In the array and slice, it returns the index of the element and the value corresponding to the index , Return... In the collection key-value Yes .
for Cyclic range The format can be right slice、map、 Array 、 String and so on . The format is as follows :
for key, value := range oldMap {
newMap[key] = value
}
In the above code key and value You can omit .
If you just want to read key, The format is as follows :
for key := range oldMap
Or so :
for key, _ := range oldMap
If you just want to read value, The format is as follows :
for _, value := range oldMap
Sample code
package main
import "fmt"
var pow = []int{
1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
}
The output of the above example is :
for Cyclic range The format can be omitted key and value, The following example :
package main
import "fmt"
func main() {
map1 := make(map[int]float32)
map1[1] = 1.0
map1[2] = 2.0
map1[3] = 3.0
map1[4] = 4.0
// Read key and value
for key, value := range map1 {
fmt.Printf("key is: %d - value is: %f\n", key, value)
}
// Read key
for key := range map1 {
fmt.Printf("key is: %d\n", key)
}
// Read value
for _, value := range map1 {
fmt.Printf("value is: %f\n", value)
}
}
The output of the above example is :
After running many times, we can find that, as we said before ,map Disorder of , This will be mentioned later
range Traverse
package main
import "fmt"
func main() {
// This is what we use range Ask for one slice And . Using arrays is very similar to this
nums := []int{
2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
// Use... On arrays range Pass in two variables, index and value . In the above example, we don't need to use the sequence number of the element , So we use whitespace "_" omitted . Sometimes we really need to know its index .
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
//range It can also be used in map The key value of is right up .
kvs := map[string]string{
"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
//range It can also be used to enumerate Unicode character string . The first parameter is the index of the character , The second is the character (Unicode Value ) In itself .
for i, c := range "go" {
fmt.Println(i, c)
}
}
The output of the above example is :
sum: 9
index: 1
a -> apple
b -> banana
0 103
1 111
for A nested loop
Go The language allows users to use loops within loops . Next, we will introduce the use of nested loops .
The following is a Go The format of language nested loop :
for [condition | ( init; condition; increment ) | Range]
{
for [condition | ( init; condition; increment ) | Range]
{
statement(s);
}
statement(s);
}
The following example uses loop nesting to output 2 To 100 Prime between :
example
package main
import "fmt"
func main() {
/* Defining local variables */
var i, j int
for i=2; i < 100; i++ {
for j=2; j <= (i/j); j++ {
if(i%j==0) {
break; // If you find a factor , It's not a prime number
}
}
if(j > (i/j)) {
fmt.Printf("%d Prime number \n", i);
}
}
}
The output of the above example is :
2 Prime number
3 Prime number
5 Prime number
7 Prime number
11 Prime number
13 Prime number
17 Prime number
19 Prime number
23 Prime number
29 Prime number
31 Prime number
37 Prime number
41 Prime number
43 Prime number
47 Prime number
53 Prime number
59 Prime number
61 Prime number
67 Prime number
71 Prime number
73 Prime number
79 Prime number
83 Prime number
89 Prime number
97 Prime number
break
Go In language break The statement is used in the following two aspects :
- Used to jump out of a loop in a loop statement , And start executing the statement after the loop .
- break stay switch( Switch statement ) In the implementation of a case The function of the post jump sentence .
- In multiple loops , You can use the label label Mark the thought break The cycle of .
break The syntax is as follows :
break
make & map function
make( aggregate )
Go Built in functions provided by language make() It can be used to flexibly create array slices .
The number of initial elements created is 5 Array slice , The initial value of the element is 0:
mySlice1 := make([]int, 5)
The number of initial elements created is 5 Array slice , The initial value of the element is 0, And reserve 10 Storage space for elements :
mySlice2 := make([]int, 5, 10)
You can also choose whether to specify this... At creation time map Initial storage capacity , Created an initial storage capacity of 100 Of map.
myMap = map[string] PersonInfo{
"1234": PersonInfo{
"1", "Jack", "Room 101,..."},
}
Create and initialize map Code for .
map( Range )
Map Is an unordered set of key value pairs .Map The most important point is through key To quickly retrieve data ,key Similar to index , The value that points to the data .
Map It's a collection , So we can iterate it like we iterate arrays and slices . however ,Map Is chaotic , We can't decide the return order , This is because Map It's using hash Table to achieve .
You can use built-in functions make You can also use map Keyword to define Map:
/* Declare variables , Default map yes nil */
var map_variable map[key_data_type]value_data_type
/* Use make function */
map_variable := make(map[key_data_type]value_data_type)
If not initialized map, Then create a nil map.nil map Cannot be used to store key value pairs
package main
import "fmt"
func main() {
var countryCapitalMap map[string]string /* Create set */
countryCapitalMap = make(map[string]string)
/* map Insert key - value Yes , The corresponding capital of each country */
countryCapitalMap [ "France" ] = " In Paris, "
countryCapitalMap [ "Italy" ] = " The Roman "
countryCapitalMap [ "Japan" ] = " Tokyo "
countryCapitalMap [ "India " ] = " New Delhi "
/* Use the key to output map values */
for country := range countryCapitalMap {
fmt.Println(country, " The capital is ", countryCapitalMap [country])
}
/* See if the element exists in the collection */
capital, ok := countryCapitalMap [ "American" ] /* If it's true , There is , Otherwise, it doesn't exist */
/*fmt.Println(capital) */
/*fmt.Println(ok) */
if (ok) {
fmt.Println("American Its capital is ", capital)
} else {
fmt.Println("American There is no capital of ")
}
}
The result of the above example is :
France The capital is In Paris,
Italy The capital is The Roman
Japan The capital is Tokyo
India The capital is New Delhi
American There is no capital of
delete() function
delete() Function to delete the elements of a collection , Parameter is map Corresponding to it key. Examples are as follows :
example
package main
import "fmt"
func main() {
/* establish map */
countryCapitalMap := map[string]string{
"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "India": "New delhi"}
fmt.Println(" Original map ")
/* Print a map */
for country := range countryCapitalMap {
fmt.Println(country, " The capital is ", countryCapitalMap [ country ])
}
/* Remove elements */ delete(countryCapitalMap, "France")
fmt.Println(" The French entry was deleted ")
fmt.Println(" After deleting the elements, the map ")
/* Print a map */
for country := range countryCapitalMap {
fmt.Println(country, " The capital is ", countryCapitalMap [ country ])
}
}
The result of the above example is :
Original map
India The capital is New delhi
France The capital is Paris
Italy The capital is Rome
Japan The capital is Tokyo
The French entry was deleted
After deleting the elements, the map
Italy The capital is Rome
Japan The capital is Tokyo
India The capital is New delhi
Go Language functions
Function definition
Functions are basic blocks of code , Used to perform a task .
Go Language has at least one main() function .
You can divide different functions by functions , Logically, each function performs the specified task .
The function declaration tells the compiler the name of the function , Return type , And parameters .
Go The language standard library provides a variety of built-in functions that can be used . for example ,len() Functions can take different types of arguments and return the length of that type . If we pass in a string, we return the length of the string , If an array is passed in , The number of elements in the array is returned .
Go The language function definition format is as follows :
func function_name( [parameter list] ) [return_types] {
The body of the function
}
Function definition resolution :
- func: The function is defined by func Start statement
- function_name: The name of the function , The parameter list and return value type constitute the function signature .
- parameter list: parameter list , Parameters are like placeholders , When a function is called , You can pass values to parameters , This value is called the actual parameter . The parameter list specifies the parameter type 、 The order 、 And the number of parameters . Parameters are optional , That is to say, a function can also contain no parameters .
- return_types: Return type , Function returns a list of values .
- return_types Is the data type of the column value . Some functions do not need to return values , In this case return_types It's not necessary .
The body of the function : Function defined code set .
The following example is max() Function code , This function passes in two integer arguments num1 and num2, And return the maximum value of these two parameters :
/* Function returns the maximum of two numbers */
func max(num1, num2 int) int {
/* Declare local variables */
var result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
Function call
When creating a function , You define what the function needs to do , Perform the specified task by calling this function .
Call function , Pass arguments to the function , And the return value , for example :
package main
import "fmt"
func main() {
/* Defining local variables */
var a int = 100
var b int = 200
var ret int
/* Call the function and return the maximum value */
ret = max(a, b)
fmt.Printf( " The maximum is : %d\n", ret )
}
/* Function returns the maximum of two numbers */
func max(num1, num2 int) int {
/* Defining local variables */
var result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
The above examples are in main() Call in function max() function , The execution result is :
The maximum is : 200
Function returns multiple values
Go A function can Return multiple values , for example :
example
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("Google", "Runoob")
fmt.Println(a, b)
}
The execution result of the above example is :
Runoob Google
Go Language function values pass values
Passing refers to copying the actual parameters into the function when calling the function , In this way, if the parameter is modified in the function , Will not affect the actual parameters .
By default ,Go Language uses value passing , That is, the actual parameters will not be affected during the call .
Go Language function references pass values
Reference passing refers to passing the address of the actual parameter to the function when the function is called , So the changes to the parameters in the function , It will affect the actual parameters .
Below we call by using reference passing swap() function :
package main
import "fmt"
func main() {
/* Defining local variables */
var a int = 100
var b int= 200
fmt.Printf(" Exchange before ,a Value : %d\n", a )
fmt.Printf(" Exchange before ,b Value : %d\n", b )
/* call swap() function * &a Point to a The pointer ,a The address of the variable * &b Point to b The pointer ,b The address of the variable */
swap(&a, &b)
fmt.Printf(" After exchanging ,a Value : %d\n", a )
fmt.Printf(" After exchanging ,b Value : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* preservation x The value on the address */
*x = *y /* take y Value is assigned to x */
*y = temp /* take temp Value is assigned to y */
}
The execution result of the above code is :
Exchange before ,a Value : 100
Exchange before ,b Value : 200
After exchanging ,a Value : 200
After exchanging ,b Value : 100
Go Language functions as arguments
Go Language can create functions flexibly , And as an argument to another function . In the following example, we initialize a variable in the defined function , This function is only for using built-in functions math.sqrt()
, Example is :
package main
import (
"fmt"
"math"
)
func main(){
/* Declare function variables */
getSquareRoot := func(x float64) float64 {
return math.Sqrt(x)
}
/* Using functions */
fmt.Println(getSquareRoot(9))
}
The execution result of the above code is :
3
边栏推荐
猜你喜欢
Base du réseau neuronal de convolution d'apprentissage profond (CNN)
[hard core dry goods] which company is better in data analysis? Choose pandas or SQL
ACM getting started Day1
JMeter 常用的几种断言方法,你会了吗?
Fundamentals of deep learning convolutional neural network (CNN)
Bitcoinwin (BCW) was invited to attend Hanoi traders fair 2022
Django uses mysqlclient service to connect and write to the database
使用easyexcel模板导出的两个坑(Map空数据列错乱和不支持嵌套对象)
【无标题】
Postman核心功能解析-参数化和测试报告
随机推荐
okcc呼叫中心有什么作用
常用运算符与运算符优先级
Summer Challenge database Xueba notes, quick review of exams / interviews~
全网最全的低代码/无代码平台盘点:简道云、伙伴云、明道云、轻流、速融云、集简云、Treelab、钉钉·宜搭、腾讯云·微搭、智能云·爱速搭、百数云
随机数生成的四种方法|Random|Math|ThreadLocalRandom|SecurityRandom
Bitcoinwin (BCW)受邀参加Hanoi Traders Fair 2022
Debezium series: idea integrates lexical and grammatical analysis ANTLR, and check the DDL, DML and other statements supported by debezium
【硬核干货】数据分析哪家强?选Pandas还是选SQL
IBM has laid off 40 + year-old employees in a large area. Mastering these ten search skills will improve your work efficiency ten times
Debezium series: modify the source code to support drop foreign key if exists FK
打新债在哪里操作开户是更安全可靠的呢
What is the function of okcc call center
Gstreamer中的task
Millimeter wave radar human body sensor, intelligent perception of static presence, human presence detection application
Microwave radar induction module technology, real-time intelligent detection of human existence, static micro motion and static perception
Flume series: interceptor filtering data
图嵌入Graph embedding学习笔记
浅浅的谈一下ThreadLocalInsecureRandom
深度學習 卷積神經網絡(CNN)基礎
Redis cluster simulated message queue