教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go语言函数类型实现接口

Go语言函数类型实现接口

发布时间:2022-02-11   编辑:jiaochengji.com
教程集为您提供Go语言函数类型实现接口等资源,欢迎您收藏本站,我们将为您提供最新的Go语言函数类型实现接口资源

Go语言函数类型实现接口——把函数作为接口来调用

函数和其他类型一样都属于“一等公民”,其他类型能够实现接口,函数也可以,本节将对结构体与函数实现接口的过程进行对比。

首先给出本节完整的代码:

<pre class="has"><code class="language-Go">package main import ( "fmt" ) // 调用器接口 type Invoker interface { // 需要实现一个Call方法 Call(interface{}) } // 结构体类型 type Struct struct { } // 实现Invoker的Call func (s *Struct) Call(p interface{}) { fmt.Println("from struct", p) } // 函数定义为类型 type FuncCaller func(interface{}) // 实现Invoker的Call func (f FuncCaller) Call(p interface{}) { // 调用f函数本体 f(p) } func main() { // 声明接口变量 var invoker Invoker // 实例化结构体 s := new(Struct) // 将实例化的结构体赋值到接口 invoker = s // 使用接口调用实例化结构体的方法Struct.Call invoker.Call("hello") // 将匿名函数转为FuncCaller类型,再赋值给接口 invoker = FuncCaller(func(v interface{}) { fmt.Println("from function", v) }) // 使用接口调用FuncCaller.Call,内部会调用函数本体 invoker.Call("hello") }</code></pre>

http://c.biancheng.net/view/58.html

到此这篇关于“Go语言函数类型实现接口”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
go 获取函数地址_Go语言基础--接口浅析
Go语言的函数、方法和接口
Go 语言到底适合干什么?
【Golang】go语言面向接口
go语言学习笔记(十三)——接口类型
2020-10-18Go语言接口
Go语言函数类型实现接口
Go语言学习3----Go语言特色
想系统学习GO语言(Golang
go run main.go 参数_Go语言入门:Hello world

[关闭]
~ ~