4

Since I've a similar function for 2 different data types:

func GetStatus(value uint8) (string) {...}
func GetStatus(name string) (string) {...}

I would want to use a way more simple like:

func GetStatus(value interface{}) (string) {...}

Is possible to create a generic function using an interface? The data type could be checked using reflect.Typeof(value)

0

1 Answer 1

2

Does what you want to do need the complexity and overhead of the reflect package? Have you considered a simple switch statement type switch?

package main

import (
    "fmt"
)

func GetStatus(value interface{}) string {
    var s string
    switch v := value.(type) {
    case uint8:
        v %= 85
        s = string(v + (' ' + 1))
    case string:
        s = v
    default:
        s = "error"
    }
    return s
}

func main() {
    fmt.Println(GetStatus(uint8(2)), GetStatus("string"), GetStatus(float(42.0)))
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.