似乎您在问这是因为您想要类型安全,所以我首先认为您的初始解决方案已经不安全了
func (m Misc) Comment () *Comment { return m.value.(*Comment)}如果您之前没有检查
IsComment过,将会感到恐慌。因此,与Volker提出的类型开关相比,该解决方案没有任何好处。
由于要对代码进行分组,因此可以编写一个确定
Misc元素是什么的函数:
func IsMisc(v {}interface) bool { switch v.(type) { case Comment: return true // ... }}但是,那也不会给您带来编译器类型检查。
如果您希望能够
Misc由编译器识别某些内容,则应考虑创建一个将某些内容标记为的接口
Misc:
type Misc interface { ImplementsMisc()}type Comment Charsfunc (c Comment) ImplementsMisc() {}type ProcessingInstructionfunc (p ProcessingInstruction) ImplementsMisc() {}这样,您可以编写仅处理杂项的函数。对象并稍后决定要在这些函数中真正要处理的内容(注释,说明等)。
如果您想模仿工会,那么据我所知,这是您写作的方式。



