golang接口

golang中的接口也可以为一个类型 

例如:

type O interface {
	Dosth(s string)string
}

type S struct {
	do O
}

  此时如何给S这个结构的do赋值呢?

必须是一个实现了O这个接口的结构      

例如:

type T struct {
}

func (t T) Dosth(s string) string{
	fmt.Println(s)
	return s+"666"
}

这个T结构就实现了O这个接口,所以我可以创建一个T,然后赋值给S的do

func main () {
	s := S{}
	t := T{}
	s.do = t
	str := s.do.Dosth("asdasd")
	fmt.Println(str)
}

猜你喜欢

转载自blog.csdn.net/qq_36980207/article/details/88861591