持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情
Go Interface理解
Java 中有接口的概念,Go 中有没有呢?
interface 是一种类型, 也可以说 interface 是一种具有一组方法的类型,这些方法定义了 interface 的行为。
- go 允许不带任何方法的
interface,这种类型的interface叫Empty interface, 其实就是interface{} - 如果一个类型实现了一个 interface 中所有方法,我们说类型实现了该 interface,
- 所以所有类型都实现了 empty interface,因为 empty interface 中不带任何方法,任何一种类型都实现了
empty interface方法, 类似Java中的Object
接口实现的例子
接口
type MysqlIncrementColumn interface {
IsNull() bool
IsUnsigned() bool
IsPk() bool
IsUpdated() bool
GetName() string
GetSqlType() string
GetStringValue() string
GetValue() (interface{}, error)
}
接口实现:
type S struct {
value interface{}
}
func (s S) IsUnsigned() bool {
return false
}
func (s S) IsPk() bool {
return false
}
func (s S) IsUpdated() bool {
//TODO implement me
panic("implement me")
}
func (s S) GetName() string {
//TODO implement me
return "flow_no"
panic("implement me")
}
func (s S) GetSqlType() string {
//TODO implement me
panic("implement me")
}
func (s S) GetValue() (interface{}, error) {
return s.value, nil
}
func (s S) IsNull() bool {
return false
}
func (s *S) GetStringValue() string {
if val, ok := s.value.(string); ok {
return val
} else {
//fmt.Println(reflect.TypeOf(s.value))
if reflect.TypeOf(s.value) == reflect.TypeOf(time.Now()) {
return util.TimeForYYYYMMDD(s.value.(time.Time))
}
}
return s.value.(string)
}
使用如下:
s := &S{"1234567890"}
fmt.println(s.GetStringValue())
判断是哪个实现类?
一般来说,判断数据类型,可以用反射。
getValue:= reflect.ValueOf(b)
如何判断 interface 变量存储的是哪种类型呢?value, ok := em.(T):
- em 是 interface 类型的变量,
- T代表要断言的类型,
- value 是 interface 变量存储的值,
- ok 是 bool 类型表示是否为该断言的类型 T。
使用如下:
switch t := i.(type) {
case *S:
fmt.Println("i store *S", t)
case *R:
fmt.Println("i store *R", t)
}