专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

十八、Go 语言 - 数据类型 interface

文章永久连接:https://tech.souyunku.com/5312

很多教程都把 interface 翻译成接口,类似于 Java 但我觉得还是把它称之为一种数据类型,它类似于 Java 中的 Object

interface 把所有的具有共性的方法定义在一起, 任何其他类型只要实现了这些方法就是实现了这个 interface

我们可以这么理解, Go 语言没有基类,如果有那么就是

interface {}  

任何一个 inteface 都是这个基类的子类,因为它们都可以向上一路转换到 interface{}

比如说

interface add  {
  add() 
}

是 的子类

语法

Go 语言定义 interface 的语法格式如下

type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

如果一个 结构体 struct 实现了一个 interface 中所有的方法,那么我们就可以说这个结构体实现了这个 interface

/* 定义结构体 */
type struct_name struct {
   /* variables */
}

/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* 方法实现 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   /* 方法实现*/
}

范例

下面的范例,我们定义了一个 interface Phone 和实现了 Phone interface 的结构体 NokiaPhone

/**
 * file: main.go
 * author: 搜云库技术团队(tech.souyunku.com)
 * Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
 */

package main

import (
    "fmt"
)

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()

}

这个范例中,我们定义了一个 interface Phone,里面有一个方法 call()

然后我们在 main 函数里面定义了一个 Phone 类型变量,并分别为之赋值为 NokiaPhone 和 IPhone

然后调用call()方法

编译运行以上范例,输出结果如下

$ go run main.go
I am Nokia, I can call you!
I am iPhone, I can call you!

干货推荐

本站推荐:精选优质专栏

附录:GOlang 教程:系列文章

未经允许不得转载:搜云库技术团队 » 十八、Go 语言 - 数据类型 interface

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们