在 Go 中创建具有未导出子结构的结构实例

Creating an instance of a structure with unexported sub-structures in Go

我正在尝试手动创建给定 here, in nlopes' Go Slack library 类型的 ReactionAddedEvent 实例。但是,未导出子类型 reactionItem,这导致我在尝试实例化对象时收到错误 ./bot_test.go:111: cannot refer to unexported name slack.reactionItem

这是我的代码:

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

当我从该代码段的第 2 行删除标识符 &slack.reactionItem 时,我得到的是错误:./bot_test.go:112: missing type in composite literal,显然。

有什么方法可以让我用我需要的参数实例化一个这种类型的对象吗?

首先,如果这里的slack指的是nlopes库,slack.ReactionAddedEvent结构体的Item字段不是指针,所以不能存地址一个 slack.reactionItem 结构到那个领域。第二,slack.reactionItemFile字段是字符串,不是结构体。

第三,即使上述情况并非如此,t/weren如果不导出类型,但导出字段本身,则不能assemble单个结构文字。相反,您必须在创建结构变量后手动设置这些字段:

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

但同样,如果您使用的是 nlopes 库,那将不起作用,因为 File 字段实际上不是一个结构: https://github.com/nlopes/slack/blob/master/websocket_reactions.go

第四,如果类型未导出,这可能是一个好兆头,表明您不应该 操作该类型的对象。在这种情况下,在 nlopes 库中,这些结构仅用于解组,然后处理来自 JSON 消息的事件。