面向接口
duck typing
- 描述事物的外部行为而非内部结构
- 严格说go(编译绑定)属于结构化类型系统,类似duck typing(动态绑定)
- 接口由使用者定义
- 接口的实现是隐式的
#python
#运行时才知道传入的retriever有没有get
#需要注释来说明接口
def download(retriever):
return retriever.get("www.imooc.com")
// c++
//编译时才知道传入的retriever有没有get
//需要注释来说明接口
template <class R>
string download(const R& retriever){
return retriever.get("www.imooc.com");
}
// java没有duck typing
//传入的参数必须实现Retriever接口,无法实现同时需要多个接口 (apache polygene解决,但是很难用)
//不是duck typing
<R extends Retriever>
String download(R r){
return r.get("www.imooc.com");
}
//同时具有python,c++的duck typing的灵活性
// 又具有java的类型检查
<R extends Retriever>
String download(R r){
return r.get("www.imooc.com");
}
- 接口变量自带指针
- 接口变量同样采用值传递,几乎不需要使用接口的指针
- 指针接收者实现只能以指针方式使用;值接收者都可以
- 表示任何类型:interface
- 错误处理 Type Assertion
- Type Switch
- 常用接口
- Stringer
- Reader
- Writer
函数式编程
函数与闭包
- 函数式编程
- 函数是一等公民:参数,变量,返回值都可以是函数
- 高阶函数
- 函数>闭包
- 纯函数
- 不能有状态,只有常量和函数
- 函数只能有一个参数
func adder()func(value int)int {
// 自由变量
sum :=0
return func(value int)int{
// 局部变量
sum+=value
return sum
}
}
func main(){
adder:=adder()
for i :=0;i<10;i++{
fmt.Println(adder(i))
}
}
# python原生支持闭包
# 使用__closure__来查看闭包的内容
def addr():
sum = 0
def f(value):
nonlocal sum
sum += value
return num
return f
过去:stl或者boost带有类似库
c++11及以后:支持闭包
auto adder(){
auto sum=0;
return [=] (int value) mutable {
sum+=value;
return sum;
};
//1.8以后:使用Function接口和Lambda表达式来创建函数对象
//匿名类或Lambda表达式均支持闭包
Function<Integer,Integer> adder(){
final Holder<Integer> sum=new Holder<>(0)
return(Integer value)->{
sum.value +=value;
return sum.value;
};
}
斐波那契
func Fibonacci() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
资源管理
defer调用
- 确保调用在函数结束时发生
- 参数在defer语句时计算
- defer列表为后进先出。栈
panic
- 停止当前函数执行
- 一直向上返回,执行每一层的defer
- 如果没有遇见recover,程序退出
- 意料之中的:使用error。如:文件打不开
- 意料之外的:使用panic。如:数组越界
recover
- 仅在defer调用中使用
- 获取panic的值
- 如果无法处理,可重新panic
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦