go语言学习五 - 接口和多态

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")
	}
}

猜你喜欢

转载自www.cnblogs.com/scala/p/9551594.html