go数据类型

1、基本数据类型

整型

int8、int16、int32和int64

uint8、uint16、uint32和uint64

uintptr

浮点型

float32和float64

复数

complex64和complex128

布尔型

bool(true和false)

字符串

string

常量

运算符优先级
1
2
3
4
5
* / % << >> & &^
+ - | ^
== != < <= > >=
&&
||

2、复合数据类型

数组(固定长度元素序列)

1
a := [2]int{1, 2}

slice(变长的序列)

1
months := [...]string{1: "January", /* ... */, 12: "December"}

内置的append函数用于向slice追加元素:

1
2
3
4
5
var runes []rune
for _, r := range "Hello, 世界" {
runes = append(runes, r)
}
fmt.Printf("%q\n", runes) // "['H' 'e' 'l' 'l' 'o' ',' ' ' '世' '界']"

map

它是一个无序的key/value对的集合

内置的make函数可以创建一个map

1
ages := make(map[string]int) // mapping from strings to ints

结构体

结构体是一种聚合的数据类型

1
2
3
4
5
6
7
8
9
10
type Employee struct {
ID int
Name string
Address string
DoB time.Time
Position string
Salary int
ManagerID int
}
var dilbert Employee

JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type Movie struct {
Title string
Year int `json:"released"`
Color bool `json:"color,omitempty"`
Actors []string
}
var movies = []Movie{
{Title: "Casablanca", Year: 1942, Color: false,
Actors: []string{"Humphrey Bogart", "Ingrid Bergman"}},
{Title: "Cool Hand Luke", Year: 1967, Color: true,
Actors: []string{"Paul Newman"}},
{Title: "Bullitt", Year: 1968, Color: true,
Actors: []string{"Steve McQueen", "Jacqueline Bisset"}}

}

结构体->json

1
2
3
4
5
6
7
data, err := json.Marshal(movies)

if err != nil {
log.Fatalf("JSON marshaling failed: %s", err)
}

fmt.Printf("%s\n", data)
1
2
3
4
[{"Title":"Casablanca","released":1942,"Actors":["Humphrey Bogart","Ingr
id Bergman"]},{"Title":"Cool Hand Luke","released":1967,"color":true,"Ac
tors":["Paul Newman"]},{"Title":"Bullitt","released":1968,"color":true,"
Actors":["Steve McQueen","Jacqueline Bisset"]}]

结构体->json(格式化输出)

1
2
3
4
5
data, err := json.MarshalIndent(movies, "", " ")
if err != nil {
log.Fatalf("JSON marshaling failed: %s", err)
}
fmt.Printf("%s\n", data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[
{
"Title": "Casablanca",
"released": 1942,
"Actors": [
"Humphrey Bogart",
"Ingrid Bergman"
]
},
{
"Title": "Cool Hand Luke",
"released": 1967,
"color": true,
"Actors": [
"Paul Newman"
]
},
{
"Title": "Bullitt",
"released": 1968,
"color": true,
"Actors": [
"Steve McQueen",
"Jacqueline Bisset"
]
}
]

3、引用类型

指针(§2.3.2)、

切片 (§4.2))

字典(§4.3)、

函数(§5)

通道(§8),

4、接口类型

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2018-2020 丁振莹
  • 访问人数: | 浏览次数:

你的每一分支持,是我努力下去的最大的力量 ٩(๑❛ᴗ❛๑)۶

支付宝
微信