Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do you create a slice of functions with different signatures? I tried the code below but its feels hack-ish. Do we just bite the bullet and use a slice interface{}?

package main

import (
    "fmt"
)

type OneParams func(string) string
type TwoParams func(string, string) string
type ThreeParams func(string, string, string) string

func (o OneParams) Union() string {
    return "Single string"
}

func (t TwoParams) Union() string {
    return "Double string"
}

func (t ThreeParams) Union() string {
    return "Triple string"
}

type Functions interface {
    Union() string
}

func Single(str string) string {
    return str
}

func Double(str1 string, str2 string) string {
    return str1 + " " + str2
}

func Triple(str1 string, str2 string, str3 string) string {
    return str1 + " " + str2 + " " + str3
}

func main() {
    fmt.Println("Slice Of Functions Program!

")

    fSlice := []Functions{
        OneParams(Single),
        TwoParams(Double),
        ThreeParams(Triple),
    }

    for _, value := range fSlice {
        switch t := value.(type) {
        case OneParams:
            fmt.Printf("One: %s
", t("one"))
        case TwoParams:
            fmt.Printf("Two: %s
", t("one", "two"))
        case ThreeParams:
            fmt.Printf("Three: %s
", t("one", "two", "three"))
        default:
            fmt.Println("Huh! What's that?")
        }
    }

    fmt.Println("

")

}

Is this just a case of trying to do too much with Go?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...