Common function using interface

Since I have a similar function for two different data types:

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

I would like to use a simpler way:

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

Is it possible to create a common function using the interface? Data type can be checked with reflect.Typeof(value)

+4
source share
1 answer

Do you need complexity and overhead in reflect package? Have you considered a simple switch type switch statement?

 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))) } 
+2
source

Source: https://habr.com/ru/post/1309250/


All Articles