接口/类型断言(二)

1.定义
Interface类型可以定义一组方法,但是这些不需要实现。并且interface不能包含任何变量。
比如:

type example interface{

        Method1(参数列表) 返回值列表
        Method2(参数列表) 返回值列表
        …
}

2.interface类型默认是一个指针

type example interface{

        Method1(参数列表) 返回值列表
        Method2(参数列表) 返回值列表
        …
}
var a example
a.Method1()

3.接口实现
a. Golang中的接口,不需要显示的实现。只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。因此,golang中没有implement类似的关键字
b. 如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个接口。
c. 如果一个变量只含有了1个interface的方部分方法,那么这个变量没有实现这个接口。
4.多态
一种事物的多种形态,都可以按照统一的接口进行操作
5.接口嵌套
一个接口可以嵌套在另外的接口,如下所示:

 type ReadWrite interface {
               Read(b Buffer) bool
               Write(b Buffer) bool
} 
type Lock interface {
               Lock()
               Unlock() 
} 
type File interface {
               ReadWrite
               Lock 
               Close() 
} 
  1. 类型断言,由于接口是一般类型,不知道具体类型,如果要转成具体类型可以采用以下方法进行转换:
var t int
var x interface{}
x = t
y = x.(int)   //转成int

var t int
var x interface{}
x = t
y, ok = x.(int)   //转成int,带检查

7.练习,写一个函数判断传入参数的类型

 func classifier(items ...interface{}) {
          for i, x := range items { 
                  switch x.(type) {
                   case bool:       fmt.Printf(“param #%d is a bool\n”, i)
                   case float64:    fmt.Printf(“param #%d is a float64\n”, i)
                   case int, int64: fmt.Printf(“param #%d is an int\n”, i)
                   case nil: fmt.Printf(“param #%d is nil\n”, i)
                   case string: fmt.Printf(“param #%d is a string\n”, i)
                    default: fmt.Printf(“param #%d’s type is unknown\n”, i)
            }
}

8.类型断言,采用type switch方式

switch t := areaIntf.(type) {case *Square:        fmt.Printf(“Type Square %T with value %v\n”, t, t) 
case *Circle:       fmt.Printf(“Type Circle %T with value %v\n”, t, t) 
case float32:       fmt.Printf(“Type float32 with value %v\n”, t)case nil:        fmt.Println(“nil value: nothing to check?”) 
default:        fmt.Printf(“Unexpected type %T”, t)}

9.空接口,Interface{}
空接口没有任何方法,所以所有类型都实现了空接口。

var a int
var b interface{}
b  = a

10.判断一个变量是否实现了指定接口
判断一个变量是否实现了指定接口

 type Stringer interface {
        String() string 
}
var v MyStruct
if sv, ok := v.(Stringer); ok {
       fmt.Printf(“v implements String(): %s\n”, sv.String()); 
} 

猜你喜欢

转载自blog.51cto.com/5660061/2347206