ARTS打卡 - 20191007~20191013
这个系列是
ARTS
打卡计划, 什么是ARTS
, 参看这里 https://time.geekbang.org/column/article/85839
Algorithm
Review
本次点评Go
官网的一篇关于反射的文章 https://blog.golang.org/laws-of-reflection
。
Because reflection builds on the type system, let's start with a refresher about types in Go.
Go is statically typed. Every variable has a static type, that is, exactly one type known and fixed at compile time:
int
,float32
,*MyType
,[]byte
, and so on. If we declaretype MyInt int var i int var j MyInt
then
i
has typeint
andj
has typeMyInt
. The variablesi
andj
have distinct static types and, although they have the same underlying type, they cannot be assigned to one another without a conversion.
理解Go
的类型系统(type system)非常重要,原文中i
和j
有不同的static type
,相同的underlying type
,并不能把一个直接赋值给另一个,而需要强制类型转换。
Here again are the laws of reflection:
Reflection goes from interface value to reflection object.
Reflection goes from reflection object to interface value.
To modify a reflection object, the value must be settable.
Once you understand these laws reflection in Go becomes much easier to use, although it remains subtle. It's a powerful tool that should be used with care and avoided unless strictly necessary.
应用反射的几个法则:
- 反射能将
interface
转化为反射对象
- 反射能将
反射对象
转化为interface
- 如果要修改一个
反射对象
,前提是它的value
是可以改变的(settable
)。
在实际应用中,往往还要有实际数据类型(int
, float
, struct
等)跟interface
的转化。
最终转化规则可以概括为反射对象 <=> interface <=> static type
。
Tip
最近开始用Go
语言在LeetCode
刷题,有个小技巧,用for i := 0 …… i ++
代替for …… range
来遍历slice,避免了循环中值拷贝,在基础测试中有时能更胜一筹。
在一道数组题的解答中,分别了用两种方法提交了两次,运行时击败人数提高了25%!