一个golang接口/组合接口demo详解

目录结构:


命名就这样了,中文注释理解也方便:上代码

先说入口main  一个目录只能有一个main 入口是我的fun.go

package main

import (

    "exfun/man"

    "fmt"

)

//定义一个接口

type Fun interface {

    Contents(string) string

}


//使用这个FUN接口的人

func user(f Fun) string {

    //传到Contents(传到的Contents是fruit.go里面的)里面

    return f.Contents("php is the best language in the world")

}


func main() {

    //传值到Apple里面 使用fun接口

    fmt.Println(dxc(&man.Fun{"open"}))  //指针传递这个open是结构体里面的string 你的结构体可以自己按需定义

}




开始说fruit.go

package man //man目录下

//定义一个结构体,可以喝和你接口的名字不一样,但是编译器会警告,还是一样了吧,然后这个结构体里面可以随意定义你需要的参数,但是我们的接口返回的是Contents 也就是一个字符串,所以你的这里面不论定义多少,返回的也只能是string 如果接口定义返回的是map[int]string 这里面返回的也只能是这样 看代码:

type Fun struct {

    Apple string

}

func (r *Fun) Contents(apple string) string {

    return apple //这个apple是前面func user 传值穿过来的

}

//第二个接口同上,不讲了,说组合接口 ,第二个接口会有注释


package main

import (

    "exfun/man"

    "fmt"

)

//定义一个接口

type Fun interface {

    Contents(string) string

}

//定义第二个接口

type Peo interface {

    Map(string) string

}

//定义一个组合接口

type FunPeo interface {

    Fun

    Peo

}

//使用FUN这个接口的人

func user(f Fun) string {

    //传到Contents里面

    return f.Contents("php is the best language in the world")

}

//使用Peo接口的人

func dxc(d Peo) string {

    return d.Map("i use this api")

}

//使用组合接口的人

func wll(s FunPeo) string {

    return s.Map("golang is the best language in the world")

}


func wlls(s FunPeo) string {

    return s.Contents("php is the best language in the world")

}

func main() {

   

    fmt.Println(wll(&man.Fun{"open"})) //这个打印的是Map这个方法

    fmt.Println(wlls(&man.Fun{"open"})) //这个打印的是Content这个方法

}


看fruit.go里面

package man

type Fun struct {

    Apple string

}

func (r *Fun) Contents(apple string) string {

    return apple //这个会是xxx is  best ……

}

func (r *Fun) Map(apple string) string {

    return r.Apple //这里会返回open 就是你在前面接的时候传入的

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容