go语言映射与结构体

文章目录

  • 映射与结构体
    • 映射
    • 结构体

映射与结构体

映射


    func main() {
	    var mmp = map[string]int{}
	    var mmp1 map[string]int
	    var mmp2 = map[string]int{"id号": 001, "学号": 1510617123}
	    fmt.Printf("type=%T,value=%v  \n", mmp, mmp)
	    fmt.Printf("type=%T,value=%v \n", mmp1, mmp1)
	    fmt.Printf("type=%T,value=%v \n", mmp2, mmp2)

	    //通过内建函数(builtin包)make
	    mmp3 := make(map[string]int)
	    fmt.Printf("type=%T,value=%v,len=%d \n", mmp3, mmp3, len(mmp3))

	    //值为任意类型,往里面填东西
	    mmp4 := make(map[string]interface{})
	    mmp4["name"] = "zzx"
	    mmp4["marid"] = false
	    mmp4["age"] = 23
	    mmp4["sex"] = "男"
	    mmp4["money"] = 0
    	printmmp(mmp4)
	    //删除键值对
	    delete(mmp4, "marid")
	    printmmp(mmp4)
	    //修改键值对
	    mmp4["money"] = 3000000000
	    printmmp(mmp4)
	    //获取(查询)值
	    value, ok := mmp4["money"]
	    if ok {
		    fmt.Println(value)
	    } else {
		    fmt.Println("没有没有money,查你妹")
    	}
	    //遍历map
	    for key, value := range mmp4 {
		    fmt.Println(key, value)
	    }

        }
        func printmmp(mmp map[string]interface{}) {
	        fmt.Printf("type=%T,value=%v \n", mmp, mmp)
        }
    type=map[string]int,value=map[]  
    type=map[string]int,value=map[] 
    type=map[string]int,value=map[学号:1510617123 id号:1] 
    type=map[string]int,value=map[],len=0 
    type=map[string]interface {},value=map[age:23 sex:男 money:0 name:zzx marid:false] 
    type=map[string]interface {},value=map[name:zzx age:23 sex:男 money:0] 
    type=map[string]interface {},value=map[name:zzx age:23 sex:男 money:3000000000] 
    3000000000
    name zzx
    age 23
    sex 男
    money 3000000000

结构体

//定义结构体
type book struct {
	name  string
	price float64
}

func main() {
	//创建对象直接对属性赋值
	b1 := book{"正统道藏", 888888}
	fmt.Printf("type=%T,value=%#v \n", b1, b1)
	//创建空白对象,逐渐对属性赋值
	b2 := book{}
	fmt.Printf("type=%T,value=%#v \n", b2, b2)
	b2.name = "法华经"
	b2.price = 34.5
	fmt.Printf("type=%T,value=%#v \n", b2, b2)
	show(b2)
	//创建bookPtr(book的指针),结构体指针给属性赋值的方式与结构体对象一样
	bookPtr := new(book)
	bookPtr.name = "圆觉经"
	bookPtr.price = 35
	fmt.Println(*bookPtr)
	show1(bookPtr)
}

//通过对象获取属性
func show(b book) {
	fmt.Println(b.name, b.price)
}

//通过指针获取属性
func show1(bPtr *book) {
	fmt.Println(bPtr.name, bPtr.price)
}

输出结果:

type=main.book,value=main.book{name:"正统道藏", price:888888} 
type=main.book,value=main.book{name:"", price:0} 
type=main.book,value=main.book{name:"法华经", price:34.5} 
法华经 34.5
{圆觉经 35}
圆觉经 35

你可能感兴趣的:(go语言)