在 golang 中,我遇到以下编译错误:
cannot use m (type MessageImpl) as type Message in assignment:
MessageImpl does not implement Message (missing FirstLine method)
使用以下代码:
type Message interface {
FirstLine() string
/* some other method declarations*/
}
type MessageImpl struct {
headers []Header
/* some other fields */
}
type Request struct {
MessageImpl
/* some other fields */
}
type Response struct {
MessageImpl
/* some other fields */
}
func (r Request) FirstLine() string {
var requestLine bytes.Buffer
requestLine.WriteString("...")
// Some more instructions
return requestLine.String()
}
func (m MessageImpl) RenderMessage() string {
var message bytes.Buffer
var msg Message = m // <=== This is the line the compiler moans about
message.WriteString(msg.FirstLine())
// Some more instructions
return message.String()
}
来自java语言,我将尝试表达我的意图:让一些接口Message定义一些由抽象类实现的方法MessageImpl。两个真正的类Request,Response应该继承MessageImpl(并实现接口Message)。这两者都定义并实现了一些更多的内部方法。
这是如何做到最好的?
相关分类