This is a creation in Article, where the information may have evolved or changed.
Today, when trying to write a simple ORM with go, I find that when you call a variadic function, you don't always use the ellipsis to expand a slice, and sometimes the compiler may make an error by using a few simple examples as a description.
We usually use an empty interface when we're unsure of the data type.
tests1(789)fmt.Println("-------------")tests1("789")
func tests1(arg interface{}) { fmt.Println("value:", arg) fmt.Println("type:", reflect.TypeOf(arg).Name())}
Output results
value: 789type: int-------------value: 789type: string
When using variable entry parameters of the same type
tests([]string{"4", "5", "6"}...)
func tests(args ...string) { for i, v := range args { fmt.Println(i, "----", v) }}
Output results
0 ---- 41 ---- 52 ---- 6
When using interface{} as a variable entry parameter
func testParams(args ...interface{}) { for i, v := range args { if s, ok := v.(string); ok { fmt.Println("----", s) } if s, ok := v.([]string); ok { for i, v := range s { fmt.Println(i, "[]----", v) } } fmt.Println(i, v) }}
Error occurred
cannot use []string literal (type []string) as type []interface {} in argument to testParams
When we see this, the answer is already on the surface.
Two solutions available here
The first of these methods
s := []string{"4", "5", "6"}var d []interface{} = []interface{}{s[0], s[1], s[2]}testParams(d...)
Results
---- 40 4---- 51 5---- 62 6
The second method of
s := []string{"4", "5", "6"}var d []interface{}d = append(d, s)testParams(d...)
Results
0 []---- 41 []---- 52 []---- 60 [4 5 6]
Summary: The arguments passed in when using interface{} as a variable input parameter do type conversions