GoLang(?)接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tangyaya8/article/details/84894925

接口

接口:从字面意思来理解,是对外开放的一个口,它的功能和字面意思很像。
那接口在编程语言中代表着什么呢?我的理解是:接口抽象了内部逻辑的实现细节,从而对外只暴露必要的参数,从另外一个角度看,接口也是一种封装,将内部实现,都装到一个对外的接口中,在面向对象的编程语言中,接口也是一种规范,在Java语言中JDBC,JNI,JPA,JMS等都是接口,也是规范,实现着和调用着只需面向规范(接口)编程,实现即可,不用关系细节。很多编程语言都有接口或者模板的语法。

duck type

Duck typing in computer programming is an application of the duck test—“If it walks like a duck and it quacks like a duck, then it must be a duck”—to determine if an object can be used for a particular purpose. With normal typing, suitability is determined by an object’s type. In duck typing, an object’s suitability is determined by the presence of certain methods and properties, rather than the type of the object itself

这是在Wikipedia上摘抄的一段关于duck type的解释,通俗来说,对接口的定义没有强制规定,只要某个接口满足某个功能,它就是那个功能,这极大的满足了接口的灵活性,在很多语言中都有这种编程方式,最典型的是python和C++中的,,但是在这两种语言中都不能在我们编写代码中判断出是不是有这个方法,go语言汲取了他们缺点,达到了在没进行编译之前就能判断出类型以及方法。

GoLang中的接口

定义一个接口:

// type + 接口名称 + interface
type Readerable interface{
//接口内的方法不用写func关键字
	Read(content string)string
}

实现接口:

//定义一个URLRead结构体
type URLRead struct{
	Content string
}
//实现接口
func (read URLRead)Read(content string) string{
	return read.Content
}

测试:

func readNews(r Readable) string {
	return r.Get("https://www.meituan.com")
}
main(){
var read Readable;
read = URLRead{Content:"www.baidu.com"}
fmt.Println(read.Read(readNews(read)))
}

猜你喜欢

转载自blog.csdn.net/tangyaya8/article/details/84894925