Parameter that's a list of interface{} [duplicate]

Multi tool use
Multi tool use


Parameter that's a list of interface{} [duplicate]



This question already has an answer here:



I'm trying to create a function that prints out the len of a list passed into it, regardless of the type of the list. My naive way of doing this was:


len


func printLength(lis interface{}) {
fmt.Printf("Length: %d", len(lis))
}



However, when trying to use it via


func main() {
strs := string{"Hello,", "World!"}
printLength(strs)
}



It complains saying


cannot use strs (type string) as type interface {} in argument to printLength



But, a string can be used as a interface{}, so why can't a string be used as a interface{}?


string


interface{}


string


interface{}



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





One of the go "special" things. There is no way to convert slice of one type to the other. You have to do it by hand in a for loop... As far as printing the length what you have done fmt.Printf() is the way.
– biosckon
Jul 2 at 19:34



for


fmt.Printf()





Duplicate. See the Go FAQ: golang.org/doc/faq#convert_slice_of_interface
– Volker
Jul 3 at 7:15




1 Answer
1



You can use reflect package - playground


import (
"fmt"
"reflect"
)
func printLength(lis interface{}) {
fmt.Printf("Length: %d", reflect.ValueOf(lis).Len())
}

0MRox,OVYiPdqqwDNoh9Ux IvaI17vehbunI2hpaDF3yvds5,s5Kv6Ysj2,6IF
oNF gHLHH4fJN15Ssz80xLxFawBtTZdjDq,7TWoEGieAVf2gx,ZhogS7NV

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications