创建动态功能

时间:2018-09-04 18:17:13

标签: go

我需要在Golang中实现现有的逻辑。一般来说,它类似于:

// Function receives an object with a variable type (struct)
func(dynObject interface{}) {

    var variableFunc ... // What should be here?

    // Some things to do depending on the input param type
    switch dynObject.(type) {
    case *objA:
        // do some job
    case *objB:
        // do some job
    }

    // ...
    // Creating and calculating some variables for the following loop
    // ...

    humans := []*Humans{ ....... }
    sum := []int{}

    for _, human := range humans {
        result := variableFunc(dynObject, human)
        sum = append(sum, result)
    }
}

如您所见-作为输入,有一个 dynObject ,它是一个结构,但也可以是任何预定义的结构。稍后有一个函数variableFunc,必须使用该对象和过程,并且处理逻辑也取决于类型。因此,类型 objA 需要的逻辑与 objB 不同。

我不知道实现此目标的正常方法。如何创建此动态函数,该函数可以将不同的结构作为输入并对其应用所需的逻辑?目前,我得到一个错误,该函数需要另一种类型作为输入。而且我希望避免出现其他情况,因为已经存在。

当然,我尝试创建一个预定义的函数,并使用接口,然后以某种方式在现有的开关盒内重新定义它,但是没有运气。我需要你的帮助

1 个答案:

答案 0 :(得分:0)

package main

import "fmt"

func main() {
    common(4)
    common("whitespace")
}
func common(a interface{}) {
    switch a.(type) {
    case int:
        div(a.(int), 2)
        break
    case string:
        sayHello(a.(string))
        break
    default:
        //nothing
    }
    return
}
func div(a, b int) {
    fmt.Printf("%d", a/b)
    return
}
func sayHello(a string) {
    fmt.Printf("%s", a)
}

main函数调用一个common函数,该函数依次调用两个具有不同函数签名的不同函数。您可以看到他们执行了不同的操作。因此,这将为不同的输入输出不同的结果。如果要在switch语句中调用不同的功能是您想要做的(我可以从您的评论中收集到很多东西),那么就应该这样做。让我知道。


  

在我的开关盒中有一件工作要做,然后结果被用于计算其他变量(在本示例的中间部分),只有在此之后,我才调用variableFunc()

package stackoverflow

import "fmt"

func common(a interface{}) {
    switch a.(type) {
    case int:
        defer func(b int) {
            fmt.Printf("%d \n", b/2)
        }(a.(int))
        break
    case string:
        defer func(b string) {
            fmt.Printf("hello %s \n", b)
        }(a.(string))
        break
    default:
        //nothing
    }

    //do something here
    fmt.Println("did something here test")
    // the function gets called after
    return
}

您可以使用defer。因此,这不是defer的常规用法。但是从技术上讲,它可以用于类似这样的事情。上述功能仅在//something完成后才能执行,我相信这是您所追求的灵活性。如果某些函数感到恐慌,则此语句将在执行和退出之间出现。因此,您必须知道自己在做什么。


或者您可以使用它,以防稍后有参数输入。

package stackoverflow

import "fmt"

func common(a interface{}) {
    var f func(interface{}, int)
    switch a.(type) {
    case int:
        f = func(s interface{}, b int) {
            fmt.Printf("%d and %d\n", s.(int)/2, b)
        }
        break
    case string:
        f = func(b interface{}, c int) {
            fmt.Printf("hello %s and %d \n", b.(string), c)
        }
        break
    default:
        //nothing
    }
    //do something here
    fmt.Println("did something here test")
    // the function gets called after
    var x int = 21

    f(a, x)

    return
}
相关问题