package main

import (
	"errors"
	"fmt"
)

func main() {

	if x, e := DOCFactory("XXX"); e == nil {
		x.Summary()
	} else {
		fmt.Println(e.Error())
	}
}

type Article struct{ Topic string }

type News struct{ Title string }

type Doc interface{ Summary() }

func (a Article) Summary() {
	fmt.Printf("Article topic is %s", a.Topic)
}

func (n News) Summary() {
	fmt.Printf("News title is %s", n.Title)
}

func DOCFactory(t string) (Doc, error) {
	switch t {
	case "Article":
		return Article{"aaa"}, nil
	case "News":
		return News{"bbb"}, nil
	default:
		return nil, errors.New("no such struct")
	}
}
posted on 2018-08-28 23:13  scala  阅读(401)  评论(0编辑  收藏  举报