golang
  • Introduction
  • 环境安装
    • vscode
    • liteide
  • 第一个Go程序
  • Go项目结构
  • Go语言命令
  • 变量
  • 数据类型
    • array
    • slice
    • map
    • struct
    • interface
    • string
    • channel
    • 类型转换
  • 循环语句
  • HTTP编程
  • init函数
Powered by GitBook
On this page
  • 函数抽象
  • 实现接口
  • 声明语义
  • 接口赋值
  • 空接口

Was this helpful?

  1. 数据类型

interface

函数抽象

interface是一组函数的抽象,我们可以为某个interface抽象一组函数,如下:

type MyInterface interface {
    Load() (int, error)
}

需要注意的是,函数名前不需要加关键字 func

实现接口

要实现一个接口,只需要实现接口中的所有函数就可以了。比如

type MyStruct struct { }

func (myStruct *MyStruct) Load() (int, error) {
        return 0, nil
}

声明语义

interface的零值为nil,所以在声明一个interface时,它的值默认为nil

var v1 MyInterface
if v1 == nil {
        fmt.PrintLn("v1 is nil")
}

接口赋值

当Struct实现了某个接口中的所有函数时,就可以把该类型的对象赋值给接口。但是这里有一个问题:是把struct对象赋值给接口,还是把struct对象的指针赋值给接口。答案是:如果struct的成员函数定义为pointerMethod,则只能将struct对象的指针赋值给接口;如果定义为valueMethod,则即可以把对象赋值给接口,也可以把对象的指针赋值给接口

例如:

type MyStruct struct { }

func (struct *MyStruct) Load() (int, error) {
        return 0, nil
}

var myInterface MyInterface = &MyStruct{}  // OK
var myInterface1 MyInterface = MyStruct{}  // Not OK

如果是下面的valueMethod实现,则两个赋值都可以,因为golang会根据valueMethod生成对应的pointerMethod

type MyStruct struct { }

func (struct MyStruct) Load() (int, error) {
        return 0, nil
}

var myInterface MyInterface = &MyStruct{}  // OK
var myInterface1 MyInterface = MyStruct{}  // OK

空接口

空接口 interface{} 有点类似于Java中的Obejct类型。例如:

var v1 interface{} = 1
var v2 interface{} = "abc"
PreviousstructNextstring

Last updated 5 years ago

Was this helpful?