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)
}
}