ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

9.1 Go Interface 基础知识学习笔记

9.1 Go Interface 基础知识学习笔记 9.1 Go Interface 基础知识学习笔记1. 接口的定义接口是一组方法签名的集合定义了行为但不实现typeShapeinterface{Area()float64}typeWriterinterface{Write([]byte)(int,error)}要点接口只声明方法签名没有实现代码任何类型只要实现了接口的所有方法就自动满足该接口不需要显式声明这叫做隐式实现duck typingGo 不像 Java 需要implements关键字2. 实现接口Rectangle 和 Circle 都实现了Area() float64方法因此它们都自动满足Shape接口typeRectanglestruct{Widthfloat64Heightfloat64}func(r Rectangle)Area()float64{returnr.Width*r.Height}typeCirclestruct{Radiusfloat64}func(c Circle)Area()float64{returnmath.Pi*c.Radius*c.Radius}同样Writer 接口定义如下typeWriterinterface{Write([]byte)(int,error)}FileWriter 和 ConsoleWriter 都实现了Write([]byte) (int, error)方法自动满足Writer接口typeFileWriterstruct{Filenamestring}func(fw FileWriter)Write(data[]byte)(int,error){fmt.Printf(Writing %d bytes to file: %s\n,len(data),fw.Filename)fmt.Printf(Content: %s\n,string(data))returnlen(data),nil}typeConsoleWriterstruct{}func(cw ConsoleWriter)Write(data[]byte)(int,error){fmt.Printf(Console: %s,string(data))returnlen(data),nil}要点没有implements、extends等关键字。只要方法签名完全匹配方法名、参数类型、返回值类型就自动实现接口。3. 接口作为函数参数 — 多态函数接收接口类型参数时可以传入任何实现了该接口的类型funcprintShapeInfo(s Shape){fmt.Printf(Shape area: %.2f\n,s.Area())}funcwriteMessage(w Writer,messagestring){w.Write([]byte(message))}不同类型传入同一个函数表现出不同行为多态rect:Rectangle{Width:5,Height:3}circle:Circle{Radius:4}printShapeInfo(rect)// 输出: Shape area: 15.00printShapeInfo(circle)// 输出: Shape area: 50.27fileWriter:FileWriter{Filename:output.txt}consoleWriter:ConsoleWriter{}writeMessage(fileWriter,Hello, File!)// 输出: Writing 12 bytes to file: output.txt// Content: Hello, File!writeMessage(consoleWriter,Hello, Console!)// 输出: Console: Hello, Console!要点函数不在乎传入的具体类型只在乎它是否实现了接口要求的方法。这就是多态——同一接口不同实现不同行为。4. 接口切片 — 存储不同类型接口类型的切片可以存储所有实现了该接口的不同类型shapes:[]Shape{rect,circle}vartotalAreafloat64for_,shape:rangeshapes{totalAreashape.Area()}fmt.Printf(Total area of all shapes: %.2f\n,totalArea)// 输出: Total area of all shapes: 65.27writers:[]Writer{fileWriter,consoleWriter}fori,writer:rangewriters{message:fmt.Sprintf(Message %d from writer\n,i1)writeMessage(writer,message)}// 输出: Writing 22 bytes to file: output.txt / Content: Message 1 from writer// Console: Message 2 from writer要点[]Shape可以同时存放 Rectangle 和 Circle[]Writer可以同时存放 FileWriter 和 ConsoleWriter。这在没有接口的语言中是无法实现的数组/切片要求所有元素类型相同。5. 接口赋值接口变量可以动态切换底层类型varshape Shape shaperect// Rectangle 实现了 Shapefmt.Printf(Shape (Rectangle) area: %.2f\n,shape.Area())// 15.00shapecircle// Circle 也实现了 Shapefmt.Printf(Shape (Circle) area: %.2f\n,shape.Area())// 50.27要点接口变量内部存储了两部分信息类型信息— 底层是什么类型Rectangle 还是 Circle值信息— 底层类型的实际数据同一个shape变量可以先后指向不同类型的值调用shape.Area()时Go 根据shape当前的底层类型选择对应的方法实现。知识点总结知识点关键概念接口定义type Name interface { 方法签名 }只声明不实现隐式实现不需要implements方法签名匹配即自动实现接口多态函数接收接口参数不同类型表现出不同行为接口切片[]Shape可存放不同类型统一遍历调用接口赋值同一个接口变量可动态切换底层类型接口内部存储 (类型, 值) 两部分信息调用时根据类型选择方法
返回列表