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

请教一个 golang 的泛型问题

  •  
  •   wtfedc · 308 天前 · 472 次点击
    这是一个创建于 308 天前的主题,其中的信息可能已经有所发展或是发生改变。
    golang 的 openai package 有这么几段
    type ChatCompletionStreamResponse struct {
    	ID      string                       `json:"id"`
    	Object  string                       `json:"object"`
    	Created int64                        `json:"created"`
    	Model   string                       `json:"model"`
    	Choices []ChatCompletionStreamChoice `json:"choices"`
    }
    type CompletionResponse struct {
    	ID      string             `json:"id"`
    	Object  string             `json:"object"`
    	Created int64              `json:"created"`
    	Model   string             `json:"model"`
    	Choices []CompletionChoice `json:"choices"`
    	Usage   Usage              `json:"usage"`
    }
    type streamable interface {
    	ChatCompletionStreamResponse | CompletionResponse
    }
    type streamReader[T streamable] struct {
    	emptyMessagesLimit uint
    	isFinished         bool
    
    	reader         *bufio.Reader
    	response       *http.Response
    	errAccumulator errorAccumulator
    	unmarshaler    unmarshaler
    }
    
    有两个问题:
    1. ChatCompletionStreamResponse | CompletionResponse 中的 struct 之间的表达式还能用|?是只能在 interface 中用吗?
    2. streamReader 的 泛型 T ,只在形参( T 不是参数,这个表达不对,大概想这个意思,你懂我)声明,struct 内部没用到啊,这么玩意义何在
    项目地址

    go-openai

    1 条回复    2023-05-25 10:33:20 +08:00
    GopherDaily
        1
    GopherDaily  
       308 天前   ❤️ 1
    1. 可以直接看语言的 spec https://go.dev/ref/spec#Interface_types
    2. method 的定义中估计用到了


    看,generic 果然好丑好抽象
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3310 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 13:31 · PVG 21:31 · LAX 06:31 · JFK 09:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.