Golang语言学习从入门到实战----接口

接口概念说明

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

当某个自定义类型要使用的时候,在根据具体情况把这些方法写出来。

基本语法

在这里插入图片描述

  • 接口里的所有方法都没有方法体,即接口的方法都是没有实现的方法。接口体现了程序设计的多态和高内聚低偶合的思想。
  • Golang中的接口,不需要显式的实现。只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。因此,Golang中没有implement这样的关键字
package main

import "fmt"

type Usb interface {
	Start()
	Stop()
}

type Phone struct {

}

func (p Phone) Start(){
	fmt.Println("手机开始工作")
}

func (p Phone) Stop(){
	fmt.Println("手机停止")
}
type Camera struct{

}
//让Camera实现Usb接口的方法
func (c Camera) Start(){
	fmt.Println("相机开始工作。。。")
}

func(c Camera) Stop(){
	fmt.Println("相机停止工作。。。")
}

type Computer struct {

}

func (c Computer) Working(usb Usb){
	usb.Start()
	usb.Stop()
}

func main() {

	computer := Computer{}
	phone := Phone{}
	camera := Camera{}

	computer.Working(phone)
	computer.Working(camera)
}

输出:

手机开始工作
手机停止
相机开始工作
相机停止工作

注意事项和细节

  1. 接口本身不能创建实例,但是可以指向一个实现了该接口的自定义类型的变量(实例)
package main

import "fmt"

type AInterface interface {
	Say()
}

type Stu struct {
	Name string
}

func (stu Stu) Say(){
	fmt.Println("Stu Say()")
}

func main() {
	var stu Stu
	var a AInterface = stu
	a.Say()
}

输出:

Stu Say()
  1. 接口中所有的方法都没有方法体,即都是没有实现的方法

  2. 在Golang中,一个自定义类型需要将某个接口的所有方法都实现,我们说这个自定义类型实现了该接口

  3. 一个自定义类型只有实现了某个接口,才能将该自定义类型的实例(变量)赋给接口类型

  4. 只要是自定义数据类型,就可以实现接口,不仅仅是结构体类型

  5. 一个自定义类型可以实现多个接口

package main

import "fmt"

type AInterface interface {
	Say()
}
type BInterface interface {
	Hello()
}
type Monster struct {

}
func (m Monster) Hello() {
	fmt.Println("Hello Hello")
}

func (m Monster) Say() {
	fmt.Println("Say Hello")
}
func main() {
	var m Monster
	var a AInterface = m
	var b BInterface = m
	a.Say()
	b.Hello()
}

输出:

Say Hello
Hello Hello
  1. Golang接口中不能有任何变量

  2. 一个接口(比如A接口)可以继承多个别的接口(比如B,C接口),这时如果要实现A接口,也必须将B,C接口的方法也全部实现

package main

import "fmt"

type AInterface interface {
	Say()
}
type BInterface interface {
	Hello()
}

type CInterface interface {
	AInterface
	BInterface
	Run()
}
type Monster struct {

}
func (m Monster) Hello() {
	fmt.Println("Hello Hello")
}

func (m Monster) Say() {
	fmt.Println("Say Hello")
}
func (m Monster) Run(){
	fmt.Println("Runing")
}
func main() {
	var m Monster
	var c CInterface = m
	c.Run()

}
  1. interface类型默认是一个指针(引用类型),如果没有对```interface初始化就使用,那么会输出nil

  2. 空接口interface{}没有任何方法,所以所有类型都实现了空接口,即我们可以把任何一个变量赋给空接口

发布了140 篇原创文章 · 获赞 50 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43442524/article/details/104819133