Map即是一种利用Key-Value方式来对应的资料格式,有点类似於Python的dict
。
意指里头的资料结构皆是由一组关键字
对应一个值
(Key-Value
)的方式存在。
var Variable = map[Type]Type{}
可以像这样bool
对应到string
package main
import "fmt"
func main() {
var prize = map[int]string{
1: "First",
2: "Second",
}
fmt.Println(prize[1])
}
运行後可得以下结果
First
透过for range
关键字,遍历造访结构内的每个元素
package main
import "fmt"
func main() {
var prize = map[int]string{
1: "First",
2: "Second",
}
for key, value := range prize {
fmt.Println(key, value)
}
}
运行後可得以下结果
1 First
2 Second
Struct就是种有着类似物件导向观念的物件集合体,你可以定义该资料集合内资料组成的结构与型别,与Python中的class
类似。
结构里面可以放多个变数(int
、string
、slice
、map
..etc)、物件甚至是结构。
首先介绍一个简单的范例:
package main
import (
"fmt"
)
type Point struct {
x float64
y float64
}
func main() {
p := Point{x: 3.0, y: 4.0}
fmt.Println(p.x)
fmt.Println(p.y)
n := new(Point)
fmt.Println(n)
fmt.Println(n.x)
fmt.Println(n.y)
}
运行後得以下结果
3
4
&{0 0}
0
0
我们可以得知使用struct
的宣告与取值相当的简单,此外new一个新的struct object之後,若无赋予里头变数值,会依照他的type给预设值。
此外,几种宣告Struct的方式如下:
package main
import "fmt"
type Res struct {
Status string `json:"status"`
Msg string `json:"msg"`
}
func main() {
res1 := new(Res)
var res2 = new(Res)
var res3 *Res
res4 := &Res{
Status: "failed",
}
fmt.Println(res1, res2, res3, res4)
fmt.Printf("%+v %+v %+v %+v",res1, res2, res3, res4)
}
运行後可得以下结果
&{ } &{ } <nil> &{failed }
&{Status: Msg:} &{Status: Msg:} <nil> &{Status:failed Msg:}
package main
import (
"fmt"
)
type Box struct {
Pencil string
Eraser string
}
type Bag struct {
Box
Book string
}
func main() {
var bag = Bag{
Box{Pencil: "Big Pencil", Eraser: "White White"},
"Ironman-2021-Go",
}
fmt.Printf("%+v", bag)
}
运行後得以下结果
{Box:{Pencil:Big Pencil Eraser:White White} Book:Ironman-2021-Go}
我们可以利用struct
做到多层次的巢状结构!
如果将main()
中的var Bag
改成 &Bag
package main
import (
"fmt"
)
type Box struct {
Pencil string
Eraser string
}
type Bag struct {
Box
Book string
}
func main() {
var bag = &Bag{
Box{Pencil: "Big Pencil", Eraser: "White White"},
"Ironman-2021-Go",
}
fmt.Printf("%+v", *bag)
}
印出bag 就要透过*
来取值
{Box:{Pencil:Big Pencil Eraser:White White} Book:Ironman-2021-Go}
如果将Bag里的Box
改成*Box
package main
import (
"fmt"
)
type Box struct {
Pencil string
Eraser string
}
type Bag struct {
*Box
Book string
}
func main() {
var bag = Bag{
&Box{Pencil: "Big Pencil", Eraser: "White White"},
"Ironman-2021-Go",
}
fmt.Printf("%+v", bag)
}
这样子就会印出bag
的位址
{Box:0xc000054020 Book:Ironman-2021-Go}
这章节为大家演绎了两种经常使用的资料结构,分别为map
与struct
,那在下个章节会在介绍function
与interface
给大家认识,敬请期待。
今天我们会利用上一篇的 分页组件 范例来做更改,不过差别在於,这次我们父子组件的沟通不是透过 pro...
今天要讲的是期货合约的相关函数。 首先是Contracts函数,就像之前文章里有使用到的一样,透过C...
-零假设和替代假设(来源:PrepNuggets) 原假设和替代假设(Null and Alter...
不知不觉,铁人赛慢慢要进入尾声了,感谢过程中队友们彼此提携,互相提醒。 在前几天中,和大家介绍了 D...
当你在开发时若不想使用编译器的话,不使用JSX也是可以开发react的。 每个JSX元素都只是呼叫 ...