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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

go - How do you create a slice of functions with different signatures?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...