当前位置:网站首页>Golang foundation -- map, array and slice store different types of data

Golang foundation -- map, array and slice store different types of data

2022-07-05 08:50:00 The hunter is eating meat

Basic knowledge of , Don't explain , Look directly at the code

package main

import (
	"fmt"
)

type User struct {
    
	ID   string
	Name string
	Age  int
}

func main() {
    
	fmt.Println("------------------- map -------------------------")
	data := map[string]interface{
    }{
    }  //  Be careful : yes 2 Two braces 

	data["num"] = 123          // int  type 
	data["str"] = "helloworld" //  String type 

	user := &User{
    ID: "1001", Name: "zhangsan", Age: 18}
	data["user1"] = user // User object type 

	for k, v := range data {
    
		fmt.Printf("k= %v , v The type is  %T ,v= %v \n", k, v, v)
	}

	fmt.Println("-----------------  Array  ---------------------")

	var paramters []interface{
    }      //  Defining slices , Be careful : Yes 1 Two braces 
	paramters = append(paramters, 456)  // int  type 
	paramters = append(paramters, " Li Si ") //  String type 
	paramters = append(paramters, user) // User object type 

	for k, v := range paramters {
    
		fmt.Printf("k= %v , v The type is  %T ,v= %v \n", k, v, v)
	}
}

Running results :

------------------- map -------------------------
k= num , v The type is  int ,v= 123                          
k= str , v The type is  string ,v= helloworld                
k= user1 , v The type is  *main.User ,v= &{
    1001 zhangsan 18} 
-----------------  Array  ---------------------            
k= 0 , v The type is  int ,v= 456                            
k= 1 , v The type is  string ,v=  Li Si                         
k= 2 , v The type is  *main.User ,v= &{
    1001 zhangsan 18}
原网站

版权声明
本文为[The hunter is eating meat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050841011525.html