V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
yangbin9317
V2EX  ›  问与答

Golang 范型问题, 如何让接口方法接受未在接口范型参数中声明的类型

  •  
  •   yangbin9317 · 2023-01-08 16:40:30 +08:00 · 699 次点击
    这是一个创建于 488 天前的主题,其中的信息可能已经有所发展或是发生改变。

    例如现有 Result 和 Option 两种类型

    type Result[T any] struct {
    	Error  err
    	Value T
    }
    
    type Option[T any] sturct {
    	None  bool
    	Some T
    }
    

    现有一个 Option[string], 我想把它转换成 int, 但是 string 可能不合法, 所以写一个函数返回 Option[int]

    func MyAtoI(string a) Option[int]
    

    但是希望给类似 Result 和 Option 这样的容器实现一种接口 I, 包含一个叫 Bind 的方法, 这个方法负责把容器打开, 把参数应用到容器的内容物上, 并返回另一个实现了接口 I 的容器, 例如

    var optionInt Option[int] = result.Bind(MyAtoI)
    

    我想象中 Bind 的签名是

    type I[T any] interface {
        Bind[U any](func(T any) I[U]) I[U] // interface method must have no type parameters
    }
    

    但是会报错: interface method must have no type parameters, 需要把类型参数放到接口签名里

    type I[T, U any] interface {
    	Bind(func(T any) I[T, U]) I[T, U]
    }
    

    但这样 Bind 返回的类型就只能是 I[T, U]了, 不符合预期, 如何让 Bind 可以返回任意的 I 呢

    3 条回复    2023-01-08 17:32:22 +08:00
    Jirajine
        1
    Jirajine  
       2023-01-08 16:44:18 +08:00
    你对 go 的类型系统抱有了过高的期待
    hsfzxjy
        2
    hsfzxjy  
       2023-01-08 17:13:00 +08:00 via Android
    golang 这破类型系统不要想玩 monad 了
    Trim21
        3
    Trim21  
       2023-01-08 17:32:22 +08:00 via Android
    go 的泛型暂时还不支持你这么写。未来倒是有可能。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1004 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:04 · PVG 06:04 · LAX 15:04 · JFK 18:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.