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

我想将一个指向函数的函数指针传递给“任何东西”。

打印从任何东西传入的东西很容易(如https://play.golang.org/p/gmOy6JWxGm0):

func printStuff(stuff interface{}) {
    fmt.Printf("Testing : %v", stuff)
    }

不过,假设我想这样做:

  1. 有多个结构

  2. 从各种功能加载数据

  3. 有一个为我调用该函数的通用打印

我在 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 main


import (

    "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)

}

让这些东西正确通过的秘诀是什么?


慕雪6442864
浏览 152回答 1
1回答

天涯尽头无女友

我不知道您是否可以控制 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())}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go