The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
input2output

interface 嵌套 interface 遇到的问题

  •  
  •   input2output · Mar 8, 2020 · 3290 views
    This topic created in 2432 days ago, the information mentioned may be changed or developed.

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

    type I interface {
    	Double() I
    }
    

    但

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

    没有办法满足这个条件

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

    6 replies  •  2020-03-08 12:26:25 +08:00
    input2output
    input2output
    OP
    Mar 8, 2020
    1
    64 views, 0 replies
    hst001
    hst001
    Mar 8, 2020❤️1
    2
    func (t T) Double() I {
    return T(t*2)
    }
    Buges
    Buges
    Mar 8, 2020❤️1
    3
    两个函数类型都不一样当然匹配不了
    两种办法,一种是接收器改成指针*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
    reus
    Mar 8, 2020❤️1
    4
    接口方法的签名必须一致,不支持协变 /逆变。
    TypeErrorNone
    TypeErrorNone
    Mar 8, 2020❤️1
    5
    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
    janxin
    Mar 8, 2020❤️1
    6
    指纹需要完全一致,你返回需要返回 I
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2518 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 14:52 · PVG 22:52 · LAX 06:52 · JFK 09:52
    ♥ Do have faith in what you're doing.