donglu7816 2014-10-19 03:41
浏览 49
已采纳

类型映射的golang匿名字段

I thought I'd be able to make an ordered map type by using anonymous fields:

type customMap struct{
    map[string]string
    ordered []string
}

where I could reference the map with customMapInstance["key"] and iterate over ordered. Alas, it appears arrays and maps are not valid anonymous fields. I suspect there's a good reason...

  • 写回答

1条回答 默认 最新

  • dongxieli3839 2014-10-19 03:54
    关注

    From the spec:

    An embedded type must be specified as a type name T or as a pointer to a non-interface type name *T, and T itself may not be a pointer type.

    You see that it mentions a "type name".

    Named types are specified by a (possibly qualified) type name; unnamed types are specified using a type literal, which composes a new type from existing types.

    In other words, a map or slice may not be anonymous unless they are defined as a named type. For example:

    type MyMap map[string]string
    
    type customMap struct{
        MyMap
        ordered []string
    }
    

    However, even if you embed MyMap or a slice type, you would still not be able to index customMap. Only fields and methods may be "promoted" when you embed. For everything else they act as just another field. In the above example, MyMap doesn't have any fields or methods and therefore is equivalent to:

    type customMap struct{
        MyMap MyMap
        ordered []string
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。