GO语言学习笔记6——接口

接口

  • 定义

    • Interface类型可以定义一组方法,但是这些不需要实现。并且interface不能

      包含任何变量

    • interface 类型默认是一个指针

    1
    2
    3
    4
    5
    6
    type example interface{
    Method1(参数列表) 返回值列表
    Method2(参数列表) 返回值列表
    }
  • 接口有点像纯虚函数的父类,用来实现多态

    • 只要一个类型实现了这个接口,这个接口就可以指向这个类型
    • 这个接口类型可以指向所有实现它的方法的自定义类型
      • 可以指向typeA,也可以指向typeB
      • 多态
        • 一种事物有多种形态,都可以按照统一的接口进行操作
  • 接口实现

    • Golang中的接口,不需要显示的实现。只要一个变量,含有接口类型中

      的所有方法,那么这个变量就实现这个接口。

    • 如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个

      接口。

    • 如果一个变量只含有了1个interface的方部分方法,那么这个变量没有实现

      这个接口。

  • 接口是用来定义一组规范

    • 面向接口编程
    • 模块和模块之间定义接口来定义格式规范
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import "fmt"
type Test interface {
Print()
Sleep()
}
type Student struct {
name string
age int
score int
}
func (p Student) Print() {
fmt.Println("name:", p.name)
fmt.Println("age:", p.age)
fmt.Println("score:", p.score)
}
func (p Student) Sleep() {
fmt.Println("student sleep")
}
func main() {
var t Test
fmt.Println("t:", t)
var stu Student = Student{
name: "stu1",
age: 20,
score: 200,
}
t = stu
t.Print()
t.Sleep()
fmt.Println("t:", t)
}
  • 接口也可以嵌套

  • 空接口里面没有任何方法

    • 意味着任何类型都实现了空接口

    • 空接口可以指向任何类型

    • 1
      2
      3
      4
      var inter interface{}
      var a int
      inter = a
      fmt.Printf("type is %T",inter) //输出为int
  • 一个实现排序接口的例子:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    package main
    import (
    "fmt"
    "math/rand"
    "sort"
    )
    type Student struct {
    Name string
    Id string
    Age int
    sortType int
    }
    type StudentArray []Student
    func (p StudentArray) Len() int {
    return len(p)
    }
    func (p StudentArray) Less(i, j int) bool {
    return p[i].Name < p[j].Name
    }
    func (p StudentArray) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
    }
    func main() {
    var stus StudentArray
    for i := 0; i < 10; i++ {
    stu := Student{
    Name: fmt.Sprintf("stu%d", rand.Intn(100)),
    Id: fmt.Sprintf("110%d", rand.Int()),
    Age: rand.Intn(100),
    }
    stus = append(stus, stu)
    }
    for _, v := range stus {
    fmt.Println(v)
    }
    fmt.Println("\n\n")
    sort.Sort(stus)
    for _, v := range stus {
    fmt.Println(v)
    }
    }

类型断言

  • 类型断言,由于接口是一般类型,不知道具体类型,如果要转成具体类型可以采用以下方法:

    1
    2
    3
    4
    var t int
    var x interface{}
    x = t
    y, ok = x.(int) //转成int,带检查
  • 传入参数,动态判断类型

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    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)
    }
    }
  • 变量slice和接口slice之间赋值操作,for range 赋值

    • 不能直接赋值

      • 1
        2
        3
        4
        var a []int
        var b []interface{}
        b = a
        //是错误的

本文标题:GO语言学习笔记6——接口

文章作者:Yang Shuai

发布时间:2019年06月10日 - 18:06

最后更新:2019年06月10日 - 18:06

原始链接:https://ysbbswork.github.io/2019/06/10/GO语言学习笔记6——接口/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!