문서 생성기를 쓰고 있습니다. DocumentItem
인터페이스가 있습니다. 이는 문서의 일부입니다.인터페이스 조각에 추가
type DocumentItem interface {
compose() string
}
예를 들어, 문서는 단락과 표로 구성됩니다.
type Paragraph struct {
text string
}
type Table struct{}
Paragraph
및 Table
DocumentItem
유형의 인터페이스에 대응한다.
func (p *Paragraph) compose() string {
return ""
}
func (t *Table) compose() string {
return ""
}
Document
유형은 content []*DocumentItem
필드가 포함되어 있습니다.
type Document struct {
content []*DocumentItem
}
나는 NewParagraph()
및 NewTable()
기능은 필요한 데이터 유형을 생성하고 content
필드에 추가 할 수 있도록 해주는 방법을 찾고 있어요.
func (d *Document) NewParagraph() *Paragraph {
p := Paragraph{}
d.content = append(d.content, &p)
return &p
}
func (d *Document) NewTable() *Table {
t := Table{}
d.content = append(d.content, &t)
return &t
}
해당 변수가 문서에 포함 된 후 해당 변수의 데이터를 수정할 수 있도록 인터페이스 포인터 조각을 사용합니다.
func (p *Paragraph) SetText(text string) {
p.text = text
}
func main() {
d := Document{}
p := d.NewParagraph()
p.SetText("lalala")
t := d.NewTable()
// ...
}
하지만 컴파일러 오류를 얻을 : 내가 DocumentItem
인터페이스 유형을 캐스팅하면
cannot use &p (type *Paragraph) as type *DocumentItem in append
cannot use &t (type *Table) as type *DocumentItem in append
, 나는 한 가지 유형의 경우 다른 다를 수 있습니다 특정 기능에 액세스 할 수 없게됩니다 . 예를 들어 단락에 텍스트를 추가하고 셀 행을 추가 한 다음 테이블의 셀에 텍스트를 추가합니다.
전혀 가능합니까? https://play.golang.org/p/uJfKs5tJ98