dousuitang5239 2019-07-22 16:01
浏览 212
已采纳

双花括号在[] interface {} {}中是什么意思

Please note this is double curly braces in this format{}{}, and not nested curly braces {{}}. I am also unsure if this is an empty interface issue, a slice issue or a struct issue. I am guessing it is a combination of at least two of these.

I am learning Golang and I have reached empty interfaces. I see I need to declare a slice of empty interfaces as

[]interface{}{}

or for instance

[]interface{}{"aa","bb"}

I don't just want to blindly start using it. Whereas I understand the idea of empty interfaces, and that an interface contains two portions of data, the value and the type, I just don't understand the {}{} structure? I learned that slices are created with make() or for instance []int{}

What is the extra {} for when using empty interfaces?

Thank you

I have googled it, and went through my tutorials. I also compared it to what I know about structs as I suspect a interface is a struct. My attempts to google golang interfaces yields mainly normal interfaces, with which I have no problem.

  • 写回答

2条回答 默认 最新

  • dounai6613 2019-07-22 16:05
    关注

    []interface{} is the type: a slice [] of empty interface interface{} (which is actually an anonymous inline type declaration). The second set of braces instantiates an instance of that type, so []interface{}{} is an empty slice of empty interface, []interface{}{"aa","bb"} is a slice of empty interface with two items. That could also be []string{"aa","bb"}, a slice of string with two items, which is the same thing with a different type (string in place of interface{}).

    You could also have a non-empty interface, like []interface{SomeFunc()}{} being an empty slice of interface{SomeFunc()}, a non-empty anonymous interface type. Or you could do it with an anonymous struct type, like []struct{Foo string}{{"bar"},{"baz"}}. Here there's even more braces - the first pair around the type definition body, the second pair around the slice literal, and within that, one pair each around two struct literals.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥15 为什么我通过html绘制的SVG折线图插入到word中坐标轴不显示出来
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 wpf程序使用过程中异常奔溃
  • ¥15 多目标优化算法在与其他算法数据对比结果判断