
golang设计时偏重组合而不是继承或是实现,所以golang没有java中常见的extended和implement关键字。golang实际上比java更灵活,对于接口的实现是一种更“自然而然”的方式——如果某个类型实现了一个接口的所有方法,则默认这个类型实现了这个接口,不用显式的声明。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
package main
import "fmt"
type readable interface { read() string }
type writable interface { write(string) string }
type text struct { }
type excel struct { }
func (this *text) () string { return "text read" }
func (this *text) write(input string) string { return "text write" }
func (this *excel) () string { return "excel read" }
func (this *excel) write(input string) string { return "excel write" }
func create(typeOf string) (readable, writable) { switch typeOf { case "t": return &text{}, &text{} case "e": return &excel{}, &excel{} } return nil, nil }
func main() { t1, t2 := create("t") fmt.Println(t1.read(), t2.write("")) e1, e2 := create("e") fmt.Println(e1.read(), e2.write("")) }
|
近期评论