您现在的位置是:网站首页> 编程资料编程资料

Go语言基础go接口用法示例详解_Golang_

2023-05-26 329人已围观

简介 Go语言基础go接口用法示例详解_Golang_

在这里插入图片描述

概述

Go 语言中的接口就是方法签名的集合,接口只有声明,没有实现,不包含变量。

语法

定义接口

 type [接口名] interface { 方法名1(参数列表) 返回值列表 方法名2(参数列表) 返回值列表 ... } 

例子

 type Isay interface{ sayHi() } 

实现接口

例子

 //定义接口的实现类 type Chinese struct{} //实现接口 func (_ *Chinese) sayHi() { fmt.Println("中国人说嗨") } 
 //中国人 type Chinese struct{} //美国人 type Americans struct{} func (this *Chinese) sayHi() { fmt.Println("中国人说嗨") } func (this Americans) sayHi() { fmt.Println("美国人说hi") } //调用 &Chinese{}.sayHi() Americans{}.sayHi() 

空接口

在Go语言中,所有其它数据类型都实现了空接口。

 interface{} 
 var v1 interface{} = 1 var v2 interface{} = "abc" var v3 interface{} = struct{ X int }{1} 

如果函数打算接收任何数据类型,则可以将参考声明为interface{}。最典型的例子就是标准库fmt包中的Print和Fprint系列的函数:

 func Fprint(w io.Writer, a ...interface{}) (n int, err error) func Fprintf(w io.Writer, format string, a ...interface{}) func Fprintln(w io.Writer, a ...interface{}) func Print(a ...interface{}) (n int, err error) func Printf(format string, a ...interface{}) func Println(a ...interface{}) (n int, err error) 

接口的组合

一个接口中包含一个或多个接口

 //说话 type Isay interface{ sayHi() } //工作 type Iwork interface{ work() } //定义一个接口,组合了上述两个接口 type IPersion interface{ Isay Iwork } type Chinese struct{} func (_ Chinese) sayHi() { fmt.Println("中国人说中国话") } func (_ Chinese) work() { fmt.Println("中国人在田里工作") } //上述接口等价于: type IPersion2 interface { sayHi() work() } 

总结

interface类型默认是一个指针使用空接口可以保存任意值不能比较空接口中的动态值定义了一个接口,这些方法必须都被实现,这样编译并使用

示例

 package main import "fmt" //中国话 type Isay interface { sayHi() } //工作 type Iwork interface { work() } //中国人 type Chinese struct{} //美国人 type Americans struct{} func (this *Chinese) sayHi() { fmt.Println("中国人说嗨") } func (this Americans) sayHi() { fmt.Println("美国人说hi") } type IPersion interface { Isay Iwork } func (_ Chinese) work() { fmt.Println("中国人在田里工作") } func main() { var chinese Isay = &Chinese{} chinese.sayHi() Americans{}.sayHi() //接口组合 var ipersion IPersion = &Chinese{} ipersion.sayHi() ipersion.work() } 

以上就是Go语言基础go接口用法示例详解的详细内容,更多关于Go 语言基础的资料请关注其它相关文章!

-六神源码网