码迷,mamicode.com
首页 > 其他好文 > 详细

Generality

时间:2017-03-23 02:53:25      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:type   并且   html   程序   class   tps   div   参数   返回   

学习了 Effective Go 中 Generality 小节的内容 https://golang.org/doc/effective_go.html#generality

由于这个小节的内容稍有点抽象,因此写了以下示例程序以便加深理解。

/* Ver1 与 Ver2 是 Version 的两种不同的具体实现。
 * NewShow 接受一个 Version 作为参数,并返回一个 Show。
 * NewShow 不管 Version 的具体实现,只要是 Version 都可以接受,
 *         并且不管 Show 的具体实现,本例子虽然只给出了一种 Show 的实现 (ShowVer)
 *         但事实上换另一种实现也是可以的。
 */

package main

import "fmt"

type Version interface {
	Is() string
}

type Show interface {
	VerNum()
}

type ShowVer struct{
	V string
}
func (s ShowVer) VerNum() {
	fmt.Println("Ver.", s.V)
}

type Ver1 struct {
	V string
}
func (v Ver1) Is() string {
	return fmt.Sprint(v.V)
}

type Ver2 struct{}
func (v Ver2) Is() string {
	return "2"
}

func main() {
	ver1 := Ver1{"1"}
	ver2 := Ver2{}
	show1 := NewShow(ver1)
	show2 := NewShow(ver2)
	show1.VerNum()
	show2.VerNum()
}

func NewShow(ver Version) Show {
	v := ver.Is()
	return ShowVer{v}
}

  

本程序的结果是,打印

Ver. 1

Ver. 2

 

Generality

标签:type   并且   html   程序   class   tps   div   参数   返回   

原文地址:http://www.cnblogs.com/ahui2017/p/6602697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!