2017-04-25 2 views
1

문서 생성기를 쓰고 있습니다. DocumentItem 인터페이스가 있습니다. 이는 문서의 일부입니다.인터페이스 조각에 추가

type DocumentItem interface { 
    compose() string 
} 

예를 들어, 문서는 단락과 표로 구성됩니다.

type Paragraph struct { 
    text string 
} 
type Table struct{} 

ParagraphTableDocumentItem 유형의 인터페이스에 대응한다.

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

답변

4

에서

전체 예는 단지 슬라이스 인터페이스의 인터페이스 포인터를 사용하지 마십시오

content []DocumentItem 

을 인터페이스 값에 싸여 동적 값이 포인터 경우, 당신은 아무것도 잃지, 당신은 지적 객체를 수정할 수있을 것이다.

이것은 변경해야 할 유일한 것입니다. 확인하려면, 나는 마지막에 인쇄 추가 된 :

fmt.Printf("%+v", p) 

출력합니다 (Go Playground에 그것을 시도) :

&{text:lalala}