网络编程
位置:首页>> 网络编程>> Go语言>> Go语言基础go接口用法示例详解

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

作者:枫少文  发布时间:2024-04-30 10:06:53 

标签:Go,基础,接口
目录
  • 概述

  • 语法

    • 定义接口

    • 实现接口

    • 空接口

    • 接口的组合

  • 总结

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

    概述

    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()
    }

    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()
    }

    来源:https://blog.csdn.net/guofeng93/article/details/92675978

    0
    投稿

    猜你喜欢

    手机版 网络编程 asp之家 www.aspxhome.com