首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
您找到你想要的搜索结果了吗?
是的
没有找到

go的interface的使用

package main import ( "fmt" ) //定义:Interface 是一组抽象方法(未具体实现的方法/仅包含方法名参数返回值的方法)的集合,有点像但又不同于其他编程语言中的 interface 。type interfaceName interface {//方法列表} //注意:1:interface 可以被任意对象实现,一个类型/对象也可以实现多个 interface,2:方法不能重载,如 eat() eat(s string) 不能同时存在 //值:声明为 interface 类型的变量,可以存储任何实现了 interface 中所有方法的类型的变量(对象)。类的值类型传递方法会自动生成对应的引用类型传递方法,反之不成立 //组合:将一个 interface1 嵌入到另一个 interface2 的声明中。其作用相当于把 interface1 的函数包含到 interface2 中,但是组合中不同有重复的方法。1.只要两个接口中的方法列表相同(与顺序无关),即为相同的接口,可以相互赋值。2. interface1 的方法列表属于另一个 interface2 的方法列表的子集,interface2 可以赋值给 interface1,反之不成立(因为方法缺失),interface2 中的方法会覆盖 interface1 中同名的方法。3.可以嵌入包中的 interface type person struct { name string age int } func (p person) printMsg() { fmt.Printf("I am %s, and my age is %d.\n", p.name, p.age) } func (p person) eat(s string) { fmt.Printf("%s is eating %s ...\n", p.name, s) } func (p person) drink(s string) { fmt.Printf("%s is drinking %s ...\n", p.name, s) } type people interface { printMsg() peopleEat //组合 peopleDrink //eat() //不能出现重复的方法 } /** //与上面等价 type people interface { printMsg() eat() drink() } */ type peopleDrink interface { drink(s string) } type peopleEat interface { eat(s string) } type peopleEatDrink interface { eat(s string) drink(s string) } //以上 person 类[型]就实现了 people/peopleDrink/peopleEat/peopleEatDrink interface 类型 type foodie struct { name string } func (f foodie) eat(s string) { fmt.Printf("I am foodie, %s. My favorite food is the %s.\n", f.name, s) } //foodie 类实现了 peopleEat interface 类型 func echoArray(a interface{}) { b, _ := a.([]int) //这里是断言实现类型转换,如何不使用就会报错 for _, v := range b { fmt.Println(v, " ") } return } //任何类型都可以是interface //要点:1interface关键字用来定义一个接口,2.Go没有implements、extends等关键字,3.实现一个接口的方法就是直接定义接口中的方法4.要实现多态,就要用指针或&object语法 func main() { //定义一个people interface类型的变量p1 var p1 people p1 = person{"zhuihui", 40} p1.printMsg() p1.drin

04

史上最全的iOS之UITextView实现placeHolder占位文字的N种方法

iOS开发中,UITextField和UITextView是最常用的文本接受类和文本展示类的控件。UITextField和UITextView都输入文本,也都可以监听文本的改变。不同的是,UITextField继承自UIControl这个抽象类。UITextView继承自UIScrollView这个实体类。这就导致了UITextView可以多行展示内容,并且还可以像UIScrollView一样滚动。而UITextField只能单独的展示一行内容。从这个角度,UITextView在功能上是优于UITextField的。 但是,众所周知,UITextField中有一个placeholder属性,可以设置UITextField的占位文字,起到提示用户输入相关信息的作用。可是,UITextView就没那么幸运了,apple没有给UITextView提供一个类似于placeholder这样的属性来供开发者使用。而开发中,我们经常会遇到既要占位文字,又要可以多行展示并且可以滚动的控件,单纯的UITextField或者UITextView都不能满足这种产品上的需求。比如,现在市面上的app大多都有一个用户反馈的入口,如下图(一)所示。下面我就把自己能够想到的方法汇总一下,让更多的开发者知道,原来有这么多方法可以实现UITextView的占位文字。

04

java接口和抽象类的异同_抽象类的控制符是什么

之前Java接口中的方法默认都是public abstract,成员变量默认都是public static final,偶然发现接口中可以有default类型的方法,才知道java8中接口可以有自己的实现了。那么jdk1.8究竟对接口做了哪些修改呢? (1) 增加default方法。default方法作用范围也是public,只是有了具体实现的方法体。对已有的接口,如果想对接口增加一个新方法,那么需要对所有实现该接口的类进行修改。而有了default方法,可以解决该问题。 (2) 新增static方法。static修饰的方法也是非抽象方法,使用同类的静态方法一样,给方法的调用带来了方便。程序入口main方法也是static,现在接口也可以运行了。 例如下面在InterfaceA中定义了一个default方法,一个static方法:

04
领券