登录
首页 >  Golang >  Go问答

在Golang中如何使用多态装饰函数的签名?

来源:stackoverflow

时间:2024-03-12 21:36:30 389浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《在Golang中如何使用多态装饰函数的签名?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我尝试应用这个著名的 golang 装饰器演讲中的装饰器,但它只对他有用,因为他装饰的所有函数都附加到一个结构体,而他只是装饰一个 do() 函数。我见过的所有其他教程也是这样做的,这很烦人。

我想用base58/64编码器函数来装饰这些函数

func SpendTx(senderID, recipientID string, amount, fee utils.BigInt, payload string, ttl, nonce uint64) (rlpRawMsg []byte, err error)
func NamePreclaimTx(accountID, commitmentID string, fee uint64, ttl, nonce uint64) (rlpRawMsg []byte, err error)
func NameClaimTx(accountID, name string, nameSalt, fee uint64, ttl, nonce uint64) (rlpRawMsg []byte, err error)
...

如您所见,参数都不同,而且它们也是纯函数,不附加到结构体。但它们都返回 []byte 和一个错误,所以这应该是可能的。


解决方案


免责声明,我所做的唯一装饰是通过嵌入结构,但一种方法可能是为您想要装饰的函数定义类型(不是绝对必要的,但会使签名更简单):

type spendtxfn = func spendtx(senderid, recipientid string, amount, fee utils.bigint, payload string, ttl, nonce uint64) (rlprawmsg []byte, err error)

现在函数可以用这种类型进行对话,装饰器函数将包含与此类型相同的调用签名

func encodedspendtx(s spendtx) spendtx {
     return func(senderid, recipientid string, amount, fee utils.bigint, payload string, ttl, nonce uint64) (rlprawmsg []byte, err error) {
        // compute decorated result 
        res, err := s(senderid, recipientid, amount, fee, payload, ttl, nonce)
        if err != nil {
          return res, err
        } 
        // encode the res
        // return encoded res
     }
}

现在您可以装饰您的 spendtx 函数:

decorated := EncodedSpendTX(originalSpendTx)

decorated(...) -> []byte, err

这样做的缺点是每个函数类型都有一个装饰器。优点是 many with my favorite being 编码易于测试并与原始逻辑分离,因此不需要对原始函数进行任何更改。

其实我觉得这就是go的http中间件通过http.handler采取的做法

https://www.alexedwards.net/blog/making-and-using-middleware

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在Golang中如何使用多态装饰函数的签名?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>