More types: structs, slices, and maps Part3

2023-10-08 16:30
文章标签 maps types structs slices part3

本文主要是介绍More types: structs, slices, and maps Part3,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.Slices of slices

Slices can contain any type, including other slices.

package mainimport ("fmt""strings"
)func main() {// Create a tic-tac-toe board.board := [][]string{[]string{"_", "_", "_"},[]string{"_", "_", "_"},[]string{"_", "_", "_"},}// The players take turns.board[0][0] = "X"board[2][2] = "0"board[1][2] = "X"board[1][0] = "0"board[0][2] = "X"for i := 0; i < len(board); i++ {fmt.Printf("%s\n", strings.Join(board[i], " "))}
}

2.Appending to a slice

It is common to append new elements to a slice, and so Go provides a built-in append function. The documentation of the built-in package describes append.

func append(s []T, vs ...T) []T

The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.

The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

package mainimport "fmt"func main() {var s []intprintSlice(s)// append works on nil slices.s = append(s, 0)printSlice(s)// The slice grow as needed.s = append(s, 1)printSlice(s)// we can add more than one element at a times = append(s, 2, 3, 4)printSlice(s)
}func printSlice(s []int) {fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

3.Range

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

package mainimport "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)}
}

4.Range continued

You can skip the index or value by assigning to _.

for i, _ := range pow
for _, value := range pow

If you only want the index, you can omit the second variable.

for i := range pow

package mainimport "fmt"func main() {pow := make([]int, 10)for i := range pow {pow[i] = 1 << uint(i) // == 2**i}for _, value := range pow {fmt.Printf("%d\n", value)}
}

5.Maps

A map maps keys to values.

The zero value of a map is nil. A nil map has no keys, nor can keys be added.

The make function returns a map of the given type, initialized and ready for use.

package mainimport "fmt"type Vertex struct {Lat, Long float64
}var m map[string]Vertexfunc main() {m = make(map[string]Vertex)m["Bell Labs"] = Vertex{40.68433, -74.39967,}fmt.Println(m["Bell Labs"])
}

6.Map literals

Map literals are like struct literals, but the keys are required.

package mainimport "fmt"type Vertex struct {Lat, Long float64
}var m = map[string]Vertex{"Bell Labs": Vertex{40.68433, -74.39967,},"Google": Vertex{37.42202, -122.08408,},
}func main() {fmt.Println(m)
}

7.Map literals continued

If the top-level type is just a type name, you can omit it from the elements of the literal.

package mainimport "fmt"type Vertex struct {Lat, Long float64
}var m = map[string]Vertex{"Bell Labs": {40.68433, -74.39967},"Google":    {37.42202, -122.08408},
}func main() {fmt.Println(m)
}

8.Mutating Maps

Insert or update an element in map m:

m[key] = elem

Retrieve an element:

elem = m[key]

Delete an element:

delete(m, key)

Test that a key is present with a two-value assignment:

elem, ok = m[key]

If key is in m, ok is true. If not, ok is false.

If key is not in the map, then elem is the zero value for the map's element type.

Note: If elem or ok have not yet been declared you could use a short declaration form:

elem, ok := m[key]

package mainimport "fmt"func main() {m := make(map[string]int)m["Answer"] = 42fmt.Println("The value:", m["Answer"])m["Answer"] = 48fmt.Println("The value:", m["Answer"])delete(m, "Answer")fmt.Println("The value:", m["Answer"])v, ok := m["Answer"]fmt.Println("The value:", v, "Present?", ok)
}

9.Function values

Functions are values too. They can be passed around just like other values.

Function values may be used as function arguments and return values.

package mainimport ("fmt""math"
)func compute(fn func(float64, float64) float64) float64 {return fn(3, 4)
}func main() {hypot := func(x, y float64) float64 {return math.Sqrt(x*x + y*y)}fmt.Println(hypot(5, 12))fmt.Println(compute(hypot))fmt.Println(compute(math.Pow))
}

10.Function closures

Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.

For example, the adder function returns a closure. Each closure is bound to its own sum variable.

package mainimport "fmt"func adder() func(int) int {sum := 0return func(x int) int {sum += xreturn sum}
}func main() {pos, neg := adder(), adder()for i := 0; i < 10; i++ {fmt.Println(pos(i),neg(-2*i),)}
}

这篇关于More types: structs, slices, and maps Part3的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/166558

相关文章

rtklib.h : RTKLIB constants, types and function prototypes 解释

在 RTKLIB 中,rtklib.h 是一个头文件,包含了与 RTKLIB 相关的常量、类型和函数原型。以下是该头文件的一些常见内容和翻译说明: 1. 常量 (Constants) rtklib.h 中定义的常量通常包括: 系统常量: 例如,GPS、GLONASS、GALILEO 等系统的常量定义。 时间常量: 如一年、一天的秒数等。 精度常量: 如距离、速度的精度标准。 2. 类型

【代码随想录训练营第42期 续Day52打卡 - 图论Part3 - 卡码网 103. 水流问题 104. 建造最大岛屿

目录 一、做题心得 二、题目与题解 题目一:卡码网 103. 水流问题 题目链接 题解:DFS 题目二:卡码网 104. 建造最大岛屿 题目链接 题解:DFS  三、小结 一、做题心得 也是成功补上昨天的打卡了。 这里继续图论章节,还是选择使用 DFS 来解决这类搜索问题(单纯因为我更熟悉 DFS 一点),今天补卡的是水流问题和岛屿问题。个人感觉这一章节题对于刚

pyspark.sql.types

示例: from datetime import datetime, datefrom decimal import Decimalfrom pyspark.sql import SparkSessionfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatType, Arr

Go-Maps

语法汇总 前面介绍的array、slice都是顺序性列表,本节的map则是无序的。 这个map和C/C++/Java的map一样,在Python中称为字典/dictionary。但Golang中map的用法更符合脚本语言的特点,和Python很像。 涉及的主要语法点: var the_map map[string]intthe_map := make(map[string]int)th

Android Google Maps

Android 谷歌地图 前言正文一、设置Google Cloud 项目二、项目配置① 设置SDK② 配置API密钥③ 配置AndroidManifest.xml 三、添加地图四、定位当前① 请求定位权限② 我的位置控件③ 获取当前位置 五、配置地图① xml配置地图② 代码配置地图③ 地图点击事件④ 管理Marker 六、地址位置编码① 坐标转地址② 地址转坐标 七、源码 前言

HTML5培训第15节课堂笔记(HTML5+maps,geolocation)

HTML5培训第15节课堂笔记 1.地理信息定位: window.οnlοad=function(){         mui.plusReady(function(){            plus.geolocation.getCurrentPosition(function(p){                latitude=p.coords.latitude;

最长的一帧学习 part3

文章目录 八、osgUtil:: SceneView::cull ()part1 初始化必要的SceneView类成员变量part2 立体显示的处理part3 执行SceneView::cullStage函数,它也是场景视图筛选工作的核心函数part3.1 首先统计场景中的遮挡节点(OccluderNode),并使用CollectOccludersVisitor访问器遍历场景中的所有节点pa

【Maps JavaScript API】基础地图的创建与实现详解

文章目录 一、概述1. Google Maps JavaScript API 简介2. Simple Map 示例概述 二、创建一个基础地图1. 引入 Google Maps JavaScript API2. 初始化地图(1) 定义地图的 HTML 容器(2) 编写 JavaScript 代码初始化地图 3. 将地图集成到网页中 三、代码分析与关键点1. 地图中心点的设置2. 地图缩放级别的

LeetCode 446. Arithmetic Slices II - Subsequence

一道长得一副dp的样子的dp题。 这道题难度不算特别大,因为看得出来肯定是dp题。因为,一个等差序列里面有好几个小的等差序列。 例如,2 4是一个等差序列,2 4 6是一个等差序列。 所以我们发现等差序列是可以扩展的。 那么就得到了,咱们的转移方程的一部分 dp[i][delta]=dp[j][delta]+1 dp[i][delta] = dp[j][delta] + 1

Result Maps collection does not contain value for frontpreviewprofitManage.cdata

Result Mapscollection does not contain value for  frontpreviewprofitManage.cdata ssi 出现上述错误主要是因为你的select标签内部的resultMap属性指向的不正确 在sql文件中只要有一个resultMap或resultType属性指向错误,则在这个文件中其余正确的语句也不能执行, 所以在出