当前位置:网站首页>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}
边栏推荐
猜你喜欢

An enterprise information integration system

STM32---ADC

STM32---IIC
实例001:数字组合 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

Guess riddles (4)

Explore the authentication mechanism of StarUML

Example 004: for the day of the day, enter a day of a month of a year to judge the day of the year?

Typical low code apaas manufacturer cases

Example 010: time to show

Example 003: a complete square is an integer. It is a complete square after adding 100, and it is a complete square after adding 168. What is the number?
随机推荐
STM32---ADC
319. 灯泡开关
Matlab tips (28) fuzzy comprehensive evaluation
Task failed task_ 1641530057069_ 0002_ m_ 000000
Business modeling | process of software model
Old Wang's esp8266 and old Wu's ws2818 light strip
Low code platform | apaas platform construction analysis
【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
Lori remote control commissioning record
Wheel 1:qcustomplot initialization template
Business modeling of software model | object modeling
剑指 Offer 05. 替换空格
猜谜语啦(2)
如何写Cover Letter?
STM32 --- configuration of external interrupt
My university
Example 004: for the day of the day, enter a day of a month of a year to judge the day of the year?
猜谜语啦(142)
Guess riddles (9)
Some pitfalls of win10 network sharing