go-variable Parameters

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.