大佬教程收集整理的这篇文章主要介绍了【GoLang笔记】浅析Go语言Interface类型的语法行为及用法,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Go不是一种典型的OO语言,它在语法上不支持类和继承的概念。
没有继承是否就无法拥有多态行为了呢?答案是否定的,Go语言引入了一种新类型—Interface,它在效果上实现了类似于C++的“多态”概念,虽然与C++的多态在语法上并非完全对等,但至少在最终实现的效果上,它有多态的影子。
那么,Go的Interface类型到底是什么呢?怎么使用呢?这正是本篇笔记试图说明的问题。
2. what is Interface type in Go ?
GoLang官网language specification文档对interface type的概念说明如下:
An interface type specifies a method set called its interface. A variable of interface typecan store a value of any typewith a method set that is any superset of thE interface. Such a type is said toimplement thE interface. The value of anuninitialized variable of interface type is nil.
说实话,这段说明对新手来说比较晦涩,这正是本篇笔记试图解释清楚的地方。
从语法上看,Interface定义了一个或一组method(s),这些method(s)只有函数签名,没有具体的实现代码(有没有联想起C++中的虚函数?)。若某个数据类型实现了Interface中定义的那些被称为"methods"的函数,则称这些数据类型实现(implement)了interface。举个例子来说明。
package main import ( "fmt" "math" ) type Abser interface { Abs() float64 } type MyFloat float64 func (f MyFloat) Abs() float64 { if f < 0 { return float64(-f) } return float64(f) } func main() { var a Abser f := MyFloat(-math.Sqrt2) a = f // a MyFloat implements Abser fmt.Println(a.Abs()) }上面的代码中,第8-10行是通过type语法声明了一个名为Abser的interface类型(Go中约定的interface类型名通常取其内部声明的method名 的er形式)。而第12-19行通过type语法声明了MyFloat类型且为该类型定义了名为Abs()的method。
type Namer interface { Method1(param_list) return_type Method2(param_list) return_type ... }上面的示例用type语法声明了一个名为Namer的interface类型(但Namer不是个具体的变量,此时内存中还没有它对应的对象)。interface 类型是可以定义变量的,也即interface type can have values,例如:
3. Interface“多态”特性实例
Go语言自带的标准Packages提供的接口很多都借助了Interface以具备“可以处理任何未知数据类型”的能力。例如被广泛使用的fmt包,其功能描述如下:
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived fromC's but are simpler.
它除了可以格式化打印Go的built-in类型外,还可以正确打印各种自定义类型,只要这些自定义数据类型实现了fmt的Print aPI入参所需的interface接口。
以fmt包的Printf()函数为例,其函数签名格式如下:
func Printf(format String,a ...interface{}) (n int,err error)它的入参除了用以描述如何格式化的'format'参数外,还需要interface类型的可变长参数。该函数在实现底层的打印行为时,要求传入 的可变长参数实现了fmt包中定义的Stringer接口,这个接口类型定义及描述如下:
type Stringer interface { String() String }Stringer is implemented by any value that has a String method,which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a String or to an unformatted printer such as Print.
package main import "fmt" type Ipaddr [4]byte func main() { addrs := map[String]Ipaddr{ "loopBACk": {127,1},"googleDNS": {8,8,8},} for n,a := range addrs { fmt.Printf("%v: %v\n",n,a) } }其输出如下:
loopBACk: [127 0 0 1] googleDNS: [8 8 8 8]现在要求按规定的格式打印:Ipaddr{1,2,3,4}应该输出为"1.2.3.4"的格式,所以Ipaddr这个自定义类型需要实现Stringer接口,实现代 码如下:
// exercise-Stringer.go package main import "fmt" type Ipaddr [4]byte // TODO: Add a "String() String" method to Ipaddr. func (ip Ipaddr) String() String { return fmt.Sprintf("%v.%v.%v.%v",ip[0],ip[1],ip[2],ip[3]) } func main() { addrs := map[String]Ipaddr{ "loopBACk": {127,a) } }
执行结果符合需求:
googleDNS: 8.8.8.8 loopBACk: 127.0.0.1
【参考资料】
1. Golang Language Specification - Methods Expression
2. Golang Language Specification - Interface Type
3. <The Way to Go - A Thorough Introduction to the Go ProgrAMMing Language>一书第11.1节
4.Go Data Structures: Interfaces
5. Go Package fmt
6. A Tour of Go - Exercise: Stringers
===================== EOF ====================
以上是大佬教程为你收集整理的【GoLang笔记】浅析Go语言Interface类型的语法行为及用法全部内容,希望文章能够帮你解决【GoLang笔记】浅析Go语言Interface类型的语法行为及用法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。