当前位置:网站首页>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}
边栏推荐
猜你喜欢
随机推荐
Daily question - input a date and output the day of the year
Some pitfalls of win10 network sharing
Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
Example 006: Fibonacci series
Chapter 18 using work queue manager (1)
Go dependency injection -- Google open source library wire
Guess riddles (6)
【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
Bluebridge cup internet of things competition basic graphic tutorial - clock selection
Shift operation of complement
Sword finger offer 06 Print linked list from end to end
leetcode - 445. Add two numbers II
287. Looking for repeats - fast and slow pointer
猜谜语啦(3)
猜谜语啦(7)
Halcon shape_ trans
696. 计数二进制子串
Is the security account given by Yixue school safe? Where can I open an account
猜谜语啦(6)
Arrangement of some library files









