duanbei1709 2016-11-28 21:47
浏览 18
已采纳

在Go中使用未导出的子结构创建结构的实例

I am trying to manually create an instance of the type ReactionAddedEvent given here, in nlopes' Go Slack library. However, the sub-type reactionItem is unexported, which leads me to receive the error ./bot_test.go:111: cannot refer to unexported name slack.reactionItem when trying to instantiate the object.

Here is my code:

m := &slack.ReactionAddedEvent{ Item: &slack.reactionItem{ File: &slack.File{ Preview: "Test", URLPrivate: "http://google.com", }, }, Reaction: "white_check_mark", }

When I remove the identifier &slack.reactionItem from line 2 in that snippet, I get instead the error: ./bot_test.go:112: missing type in composite literal, obviously.

Is there any way for me to instantiate an object of this type with the parameters I need?

  • 写回答

1条回答 默认 最新

  • duanci6484 2016-11-28 22:03
    关注

    First, if slack here refers to the nlopes library, the slack.ReactionAddedEvent structure's Item field is not a pointer, so you can't store an address of a slack.reactionItem struct into that field anyway. Second, the File field of slack.reactionItem is a string, not a structure.

    Third, even if the above isn't/weren't the case, if the types are not exported, but the fields themselves are, you can't assemble the structure in a single literal. Instead, you'll have to manually set those fields after creating the structure variable:

    m := &slack.ReactionAddedEvent{Reaction: "white_check_mark"}
    m.Item.File.Preview = "Test"
    m.Item.File.URLPrivate = "http://google.com"
    

    But again, if you're using the nlopes library, that won't work because the File field isn't actually a structure: https://github.com/nlopes/slack/blob/master/websocket_reactions.go

    And fourth, if the type isn't exported, that's probably a good sign that you shouldn't be manipulating objects of that type. In this case, in the nlopes library, those structures are only intended to be used for unmarshalling and then handling events from JSON messages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大