当前位置:网站首页>golang 基础 ——map、数组、切片 存放不同类型的数据
golang 基础 ——map、数组、切片 存放不同类型的数据
2022-07-05 08:41:00 【猎人在吃肉】
基础知识,不解释,直接看代码
package main
import (
"fmt"
)
type User struct {
ID string
Name string
Age int
}
func main() {
fmt.Println("------------------- map -------------------------")
data := map[string]interface{
}{
} // 注意:是2个大括号
data["num"] = 123 // int 类型
data["str"] = "helloworld" // 字符串类型
user := &User{
ID: "1001", Name: "zhangsan", Age: 18}
data["user1"] = user // User对象类型
for k, v := range data {
fmt.Printf("k= %v , v的类型是 %T ,v= %v \n", k, v, v)
}
fmt.Println("----------------- 数组 ---------------------")
var paramters []interface{
} // 定义切片,注意:有1个大括号
paramters = append(paramters, 456) // int 类型
paramters = append(paramters, "李四") // 字符串类型
paramters = append(paramters, user) // User对象类型
for k, v := range paramters {
fmt.Printf("k= %v , v的类型是 %T ,v= %v \n", k, v, v)
}
}
运行结果:
------------------- map -------------------------
k= num , v的类型是 int ,v= 123
k= str , v的类型是 string ,v= helloworld
k= user1 , v的类型是 *main.User ,v= &{
1001 zhangsan 18}
----------------- 数组 ---------------------
k= 0 , v的类型是 int ,v= 456
k= 1 , v的类型是 string ,v= 李四
k= 2 , v的类型是 *main.User ,v= &{
1001 zhangsan 18}
边栏推荐
- Xrosstools tool installation for X-Series
- 319. Bulb switch
- Shell script
- 实例009:暂停一秒输出
- STM32 lights up the 1.8-inch screen under Arduino IDE
- [matlab] matlab reads and writes Excel
- 2020-05-21
- Guess riddles (8)
- MATLAB skills (28) Fuzzy Comprehensive Evaluation
- Sword finger offer 09 Implementing queues with two stacks
猜你喜欢
随机推荐
猜谜语啦(7)
Guess riddles (4)
Apaas platform of TOP10 abroad
UE pixel stream, come to a "diet pill"!
每日一题——输入一个日期,输出它是该年的第几天
Classification of plastic surgery: short in long long long
Cmder of win artifact
Wheel 1:qcustomplot initialization template
[three tier architecture]
287. Looking for repeats - fast and slow pointer
图解八道经典指针笔试题
实例004:这天第几天 输入某年某月某日,判断这一天是这一年的第几天?
Sword finger offer 09 Implementing queues with two stacks
Guess riddles (5)
ABC#237 C
Old Wang's esp8266 and old Wu's ws2818 light strip
Esphone retrofits old fans
猜谜语啦(6)
Dynamic dimensions required for input: input, but no shapes were provided. Automatically overriding
319. 灯泡开关