V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
input2output
V2EX  ›  Go 编程语言

interface 嵌套 interface 遇到的问题

  •  
  •   input2output · 2020-03-08 10:55:01 +08:00 · 2425 次点击
    这是一个创建于 1509 天前的主题,其中的信息可能已经有所发展或是发生改变。

    标题表述可能不准确,直接上代码
    比如

    type I interface {
    	Double() I
    }
    

    type T int
    
    func (t T) Double() T {
    	return t*2
    }
    

    没有办法满足这个条件

    想请教一下各位,如果想实现这类操作,该如何处理,谢谢

    6 条回复    2020-03-08 12:26:25 +08:00
    input2output
        1
    input2output  
    OP
       2020-03-08 11:08:25 +08:00
    64 views, 0 replies
    hst001
        2
    hst001  
       2020-03-08 11:09:40 +08:00   ❤️ 1
    func (t T) Double() I {
    return T(t*2)
    }
    Buges
        3
    Buges  
       2020-03-08 11:28:26 +08:00   ❤️ 1
    两个函数类型都不一样当然匹配不了
    两种办法,一种是接收器改成指针*T 直接修改,去掉返回值。
    如果你非要传值的话,可以包装一层空的 interface{},使用时再释放出来,如下:

    type IT interface{
    Foo() interface{}
    }

    type CT int

    func (c CT)Foo() interface{} {
    return interface{}(c*2)
    }

    func main(){
    var v IT = CT(2)
    v = v.Foo().(IT)
    }



    楼上那种做法比较 expedient,如果要满足多个 interface 就不行了。
    reus
        4
    reus  
       2020-03-08 11:36:32 +08:00   ❤️ 1
    接口方法的签名必须一致,不支持协变 /逆变。
    TypeErrorNone
        5
    TypeErrorNone  
       2020-03-08 12:15:57 +08:00   ❤️ 1
    package main

    import "fmt"

    type People interface {
    Get() People
    }

    type Teacher struct {

    }

    func (Teacher) Get() People {
    return Teacher{}
    }

    func main() {

    t := Teacher{}
    fmt.Println(t.Get())

    }
    janxin
        6
    janxin  
       2020-03-08 12:26:25 +08:00   ❤️ 1
    指纹需要完全一致,你返回需要返回 I
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5836 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 74ms · UTC 06:22 · PVG 14:22 · LAX 23:22 · JFK 02:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.