golang interface {} 的类型断言和数组和接口作为map的 value 类型

6 篇文章 0 订阅

interface{} 类型断言:

func pocInterfacePara(para interface{}){
    // 重点是:
    // 当参数可能是整形也可能是字符串类型时,就可以把形参类型定义为 interface{} 类型,该类型形参可以接任何类型的实参
    // 当需要把 interface 转换为某个具体的类型时可以 para.(xxx) 即可,比如转换为int: para(int)
	fmt.Println("In the pocInterfacePara, the paras =")
	fmt.Println(para)
	fmt.Printf("1para 的数据类型是 %T\n", para)
    fmt.Println("2para 的数据类型是:", reflect.TypeOf(para))
	switch para.(type){
	case string:
		fmt.Println("this is string")
	case int:
		fmt.Println("this is int")
	default:
		fmt.Println("this is neither string nor int")
	}
}

fmt.Println("In the InterfaceKeyPoint0: 函数参数类型是接口类型")
pocInterfacePara(123)
pocInterfacePara("hello")
pocInterfacePara([]string{"hello", "china"})

interface{} 数组

func pocInterfacePara2(para []interface{}){
	fmt.Println("In the pocInterfacePara2, the paras =")
	fmt.Println(para)
}


var paraArray []interface{}
paraArray = append(paraArray, "hello")
paraArray = append(paraArray, 123)
pocInterfacePara2(paraArray)

接口作为map的VALUE类型

E:\workspace_go\pkg\mod\github.com\beego\beego\v2@v2.0.1\core\config\config.go

// Config is the adapter interface for parsing config file to get raw data to Configer.
type Config interface {
	Parse(key string) (Configer, error)
	ParseData(data []byte) (Configer, error)
}

var adapters = make(map[string]Config)    ---这是一个全局变量---

// Register makes a config adapter available by the adapter name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, adapter Config) {
	if adapter == nil {
		panic("config: Register adapter is nil")
	}
	if _, ok := adapters[name]; ok {
		panic("config: Register called twice for adapter " + name)
	}
	adapters[name] = adapter
}



E:\workspace_go\pkg\mod\github.com\beego\beego\v2@v2.0.1\core\config\ini.go
// IniConfig implements Config to parse ini file.
type IniConfig struct {

}

// Parse creates a new Config and parses the file configuration from the named file.
func (ini *IniConfig) Parse(name string) (Configer, error) {
	return ini.parseFile(name)
}

func (ini *IniConfig) parseFile(name string) (*IniConfigContainer, error) {
	data, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, err
	}
	return ini.parseData(filepath.Dir(name), data)
}


func init() {
	Register("ini", &IniConfig{})  ---调用 Register() 方法,参数是指针类型---

	err := InitGlobalInstance("ini", "conf/app.conf")
	if err != nil {
		logs.Warn("init global config instance failed. If you donot use this, just ignore it. ", err)
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值