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

golang interface

时间:2018-11-13 20:35:52      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:div   调用   分享   ret   默认   ola   highlight   变量   pre   

接口定义

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

type Interface interface {
  test1(a, b int) bool
  test2()
}

interface类型默认是一个指针

 空接口(a interface{})可以被任何类型所实现,如动物可以被猫、狗、人等实现,反之人不一定能实现动物

func main() {
  var a interface{}

  var b int
  a = b

  fmt.Printf("%T\n", a)

  var s string
  a = s

  fmt.Printf("%T", a)
}

技术分享图片

接口只是一种规范,并没有实现,不能直接调用
type testInterface int

func (t testInterface) test1(a, b int) bool {
	return a < b
}

func (t testInterface) test2() {
	fmt.Println("test2")
}

func main() {
	var a Interface
	a.test2()
}

技术分享图片

 

接口实现

Golang中的接口,不需要显示的实现。只要一个变量,含有接口类型中的所有方法,那么这个变量就实现这个接口。因此,golang中没有implement 类似的关键字。

type testInterface int

func (t testInterface) test1(a, b int) bool {
  return a < b
}

func (t testInterface) test2() {
  fmt.Println("test2")
}

func main() {
  var a testInterface
  fmt.Printf("%T\n", a.test1(1, 2))
  a.test2()
}

技术分享图片

如果一个变量含有了多个interface类型的方法,那么这个变量就实现了多个 接口。

 

golang interface

标签:div   调用   分享   ret   默认   ola   highlight   变量   pre   

原文地址:https://www.cnblogs.com/LC161616/p/9953737.html

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