Passing interface{} or []interface{} in Golang

前端 未结 1 1107
别跟我提以往
别跟我提以往 2021-01-29 11:00

With this snippet, why does it allow interface{} to pass into the function but not []interface. And what\'s the difference? I know what the error says (have commented it into th

相关标签:
1条回答
  • 2021-01-29 11:39

    The type interface{} can be used as a very generic type that would allow any other type to be assigned to it.

    So if a function receives interface{}, you can pass any value to it.

    That is because in Go, for a type to satisfy an interface it must just implement all methods the interface declares.

    Since interface{} is an empty interface, any type will satisfy it.

    On the other hand, for a type to satisfy []interface{} it must be an actual slice of empty interfaces.

    So if you need a generic function that can receive any value, just use interface{} as you show in your example.

    Note that interface{} will allow you to pass in either value or pointer references, so you can pass in pointers or values indistinctly to that function.

    0 讨论(0)
提交回复
热议问题