为了账号安全,请及时绑定邮箱和手机立即绑定

函数指针作为“返回接口{}”的参数

函数指针作为“返回接口{}”的参数

Go
慕雪6442864 2022-04-26 14:28:52
我想将一个指向函数的函数指针传递给“任何东西”。打印从任何东西传入的东西很容易(如https://play.golang.org/p/gmOy6JWxGm0):func printStuff(stuff interface{}) {     fmt.Printf("Testing : %v", stuff)     }不过,假设我想这样做:有多个结构从各种功能加载数据有一个为我调用该函数的通用打印我在 Play ( https://play.golang.org/p/l3-OkL6tsMW ) 中尝试了这个,我收到以下错误:./prog.go:35:12: 不能在 printStuff 的参数中使用 getStuff1 (type func() SomeObject) 作为类型 FuncType./prog.go:36:12:不能在 printStuff 的参数中使用 getStuff2 (type func() SomeOtherObject) 作为类型 FuncType万一播放的东西被删除,这是我试图弄清楚如何开始工作的代码:package mainimport (    "fmt")type SomeObject struct {    Value string}type SomeOtherObject struct {        Value string}type FuncType func() interface{}func getStuff1() SomeObject {    return SomeObject{        Value: "Hello, world!",    }}func getStuff2() SomeOtherObject {    return SomeOtherObject{        Value: "Another, hello!",    }}func printStuff(toCall FuncType) {    stuff := toCall()    fmt.Printf("Testing : %v", stuff)}func main() {    printStuff(getStuff1)    printStuff(getStuff2)}让这些东西正确通过的秘诀是什么?
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

我不知道您是否可以控制 and 的返回值contra.Load(),policy.Load()例如,因此可能有更好的方法,但假设这些方法无法修改,这将允许您消除大量样板文件,而无需任何花哨的操作:


func boilerplate(tram *TrapLapse, operation *TrapOperation, loader func() interface{}) {

    loaded := loader()

    err := trap.SnapBack(operation).send(loaded);


    // default error handling

    // logging

    // boilerplate post-process

}


func resendContraDevice(trap *TrapLapse, operation *TrapOperation) {

    boilerplate(trap, operation, func() interface{} { return contra.Load() })

}


func resendPolicyDevice(trap *TrapLapse, operation *TrapOperation) {

    boilerplate(trap, operation, func() interface{} { return policy.Load() })

}

如果没有更复杂的,您还可以进一步简化:


func boilerplate(tram *TrapLapse, operation *TrapOperation, loaded interface{}) {

    err := trap.SnapBack(operation).send(loaded);


    // default error handling

    // logging

    // boilerplate post-process

}


func resendContraDevice(trap *TrapLapse, operation *TrapOperation) {

    boilerplate(trap, operation, contra.Load())

}


func resendPolicyDevice(trap *TrapLapse, operation *TrapOperation) {

    boilerplate(trap, operation, policy.Load())

}


查看完整回答
反对 回复 2022-04-26
  • 1 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号