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


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())
}

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages