zoukankan      html  css  js  c++  java
  • go中的map[Interface{}]Interface{}理解

    map里面的k,v支持很多的类型。对于go来说也是,go中有个接口的概念,任何对象都实现了一个空接口。那么我们把map里面的k,v都用interface去定义,当我们在使用这个map的时候,我们可以把任何类型的参数传入到,这个map中。真的可以吗,下面我们来看下代码。

      

    package main
    
    
    import (
    	"fmt"
    )
    
    func main() {
    
    	mapInterface := make(map[interface{}]interface{})
    	mapString := make(map[string]string)
    
    	mapInterface["k1"] = 1
    	mapInterface[3] = "hello"
    	mapInterface["world"] = 1.05
    	mapInterface["rt"] = true
    
    	for key, value := range mapInterface {
    		strKey := fmt.Sprintf("%v", key)
    		strValue := fmt.Sprintf("%v", value)
    
    		mapString[strKey] = strValue
    	}
    
    	fmt.Printf("%#v", mapString)
    }
    

      输出结果

     我们可以看到,不管int类型,bool类型,都可以传值到map中。

     我们最后只需要把他装换成我们需要的类型就可以了

  • 相关阅读:
    POJ 2136
    POJ 2121
    POJ 2127
    POJ 2126
    POJ 2109
    POJ 2105
    POJ 2101
    POJ 2075
    Uboot — 配置过程
    Uboot — 编译体验
  • 原文地址:https://www.cnblogs.com/ricklz/p/9494661.html
Copyright © 2011-2022 走看看