Type of function parameter changes

65 views
Skip to first unread message

Amarjeet Anand

unread,
May 16, 2020, 10:06:32 PM5/16/20
to golang-nuts
Hi

Why does the type of a parameter passed to another function changes?
For example: 
func P(args ...interface{}) {
print("\n", args)
}

func print(seperator string, args ...interface{}) {
for _, arg := range args {
fmt.Println("arg type: ", reflect.TypeOf(arg))

str := ""
switch v := arg.(type) {
case byte:
str = string(v)
case rune:
str = string(v)
case int:
str = strconv.Itoa(v)
case int64:
str = strconv.FormatInt(v, 10)
case string:
str = v
}
out.WriteString(str + seperator)
}
}

Calling P("one"[2]) gives type as  []interface {}
where as directly calling print("one"[2]) gives type as byte

Why is it like this? 
And any way i can achieve this without putting switch in P() function?









Jesse McNelis

unread,
May 16, 2020, 10:23:10 PM5/16/20
to Amarjeet Anand, golang-nuts
Hi,

You can simply do:

func P(args ...interface{}) {
   print("\n", args...)
}

The problem you encountered was that you were passing the args as a single argument to print()

The 'var args' syntax collects the arguments and puts them in a slice. So args in P() is a []interface{}.
You then pass that whole []interface{} as an argument to print(), for args in print() gets a []interface{} where the first item in the slice is an interface{} that contains a []interface{}, which isn't what you wanted.

By using the spread operator when passing the args slice to print(), you get the pass the args slices multiple arguments to print().

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CANFuhy-7NbdMw6UynmUS9HnakVpUaJ_SCP8vkr11Z27LcLnrPA%40mail.gmail.com.


--
=====================
http://jessta.id.au

Amarjeet Anand

unread,
May 16, 2020, 11:15:27 PM5/16/20
to Jesse McNelis, golang-nuts
Hi Jesse
Thanks for the response. 
Got it.
Reply all
Reply to author
Forward
0 new messages