惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
T
The Blog of Author Tim Ferriss
Microsoft Azure Blog
Microsoft Azure Blog
U
Unit 42
IT之家
IT之家
D
DataBreaches.Net
Y
Y Combinator Blog
B
Blog RSS Feed
F
Fortinet All Blogs
GbyAI
GbyAI
V
Visual Studio Blog
博客园 - 叶小钗
Google DeepMind News
Google DeepMind News
美团技术团队
L
LangChain Blog
N
Netflix TechBlog - Medium
G
Google Developers Blog
Recent Announcements
Recent Announcements
T
Tailwind CSS Blog

博客园 - 远洪

大模型常用术语 windows 使用sshAgent 加载秘钥 再次认识java反射 再次认识java注解 再次认识java泛型 java中类的分类 java类中的成员变量,静态变量与局部变量 再谈java枚举enum 使用CCProxy让手机访问电脑能访问的网址 playwright启动后报错net::ERR_CERT_COMMON_NAME_INVALID 解决方法 debian 或ubuntu安装使用tigervnc python 实例属性、类属性、实例方法、类方法、静态方法 python面向对象封装,私有变量 docker compose使用 docker 自定义网络 Dockerfile 使用 golang进程(主线程)与协程 go语言多态中的类型断言 java中的多态与golang中的多态
golang 定义接口
远洪 · 2024-01-11 · via 博客园 - 远洪

一、定义接口语法

type 接口名 interface {
    method1(参数列表) 返回值列表
    method2(参数列表) 返回值列表
}   
  1. 接口中所有方法都没有方法体
  2. 接口中不能包含任何变量
  3. golang中没有implements 关键字,因此不需要显示的去实现接口;在golang中只要一个变量,包含了接口类型的所有方法,那么这个变量就实现了这个接口。

二、案例

package main

import (
    "fmt"
)

type Usb interface{
    Connect()
    DisConnect()
}

type Phone struct{
}

/*
*  Phone实现了Usb 接口(是指实现了Usb接口的所有方法)
*/
func(p Phone) Connect(){
    fmt.Println("手机连接...")
}

func(p Phone) DisConnect(){
    fmt.Println("手机断开连接...")
}

type Camera struct{
}

func(c Camera) Connect(){
    fmt.Println("相机连接...")
}

func(c Camera) DisConnect(){
    fmt.Println("相机断开连接...")
}

type  Computer struct{
}

func(c Computer) Working(u Usb){
    u.Connect()
    u.DisConnect()
}

func main(){
    phone := Phone{}
    camera := Camera{}
    computer := Computer{}
    computer.Working(phone)
    computer.Working(camera)
}

运行结果如下: