码迷,mamicode.com
首页 > 其他好文 > 详细

Go接口

时间:2020-01-25 10:28:16      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:UNC   highlight   package   print   idt   height   接口   应用   port   

1. 接口介绍

技术图片

技术图片

2. 应用场景

技术图片

技术图片

 3. 注意事项

技术图片

package main

import (
	"fmt"
)

type AInterface interface {
	Say()
}

type Stu struct {
}

func (m Stu) Say() {
	fmt.Println("Monster Say()~~")
}

func main() {
	var stu Stu //结构体变量,实现了 Say() 实现了 AInterface
	var a AInterface = stu
	a.Say()

}

技术图片

 技术图片

package main

import (
	"fmt"
)

type integer int

func (i integer) Say() {
	fmt.Println("integer Say i =", i)
}

type AInterface interface {
	Say()
}

func main() {

	var i integer = 10
	var b AInterface = i
	b.Say() // integer Say i = 10

}

技术图片

package main

import (
	"fmt"
)

type AInterface interface {
	Say()
}

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

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

func (m Monster) Say() {
	fmt.Println("Monster Say()~~")
}

func main() {
	//Monster实现了AInterface 和 BInterface
	var monster Monster
	var a2 AInterface = monster
	var b2 BInterface = monster
	a2.Say()
	b2.Hello()
}

技术图片

package main
import (
	_"fmt"
	"fmt"
)

type BInterface interface {
	test01()
}

type CInterface interface {
	test02()
}

type AInterface interface {
	BInterface
	CInterface
	test03()
}

//如果需要实现AInterface,就需要将BInterface CInterface的方法都实现
type Stu struct {
}
func (stu Stu) test01() {
	fmt.Println("enen")

}
func (stu Stu) test02() {

}
func (stu Stu) test03() {

}


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

}

技术图片

 技术图片

package main
import (
	"fmt"
)

type Stu struct {
}
func (stu Stu) test01() {

}
func (stu Stu) test02() {

}
func (stu Stu) test03() {

}

type T  interface{

}

func main() {
	var stu Stu
	var t T = stu //t是空接口,可以把任何变量赋值给它
	fmt.Println(t) //{}
	var t2 interface{}  = stu //interface{}表示空接口
	var num1 float64 = 8.8
	t2 = num1 //可以把任何变量给空接口
	t = num1
	fmt.Println(t2, t) //8.8 8.8

}

 

Go接口

标签:UNC   highlight   package   print   idt   height   接口   应用   port   

原文地址:https://www.cnblogs.com/yzg-14/p/12232763.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!