golang reflectgolang
go blog随笔orm
其中method prying 和compact format都涉及到了reflect包。那接下来咱们就说说golang 的reflect吧。blog
reflection是基于类型系统(type system)的, 而go语言是静态类型的,于是每一个变量都有一个静态类型(即肯定的而且编译时固定的类型),int, []byte, float32, *MyType等等。接口
若是咱们声明string
```it
type MyInt intio
var i int编译
var j MyInttable
```ast
那么i是int类型,j是MyInt类型,i和j拥有不一样的静态类型,尽管他们的基础类型(underlying type)一致,不通过类型转换也不能直接赋值。
type一个重要的分类是interface types,其实意思就是接口也是go的一种类型。
空的接口类型为:interface{}
reflection法则:
1. reflection goes from interface value to reflection object
reflect包含有两个类型,Type和Value, 以及常常用到的2个简单的方法reflect.Typeof(), reflect.Valueof, 解析了interface中的类型和值。
```
var x float64 = 3.4
fmt.Println("type", reflect.TypeOf(x))
```
打印:type: float64
2. reflection goes from reflection object to interface value
3. to modify a reflection object, the value must be settable
可不能够设置是由reflection object 是否holds原始信息决定的。
----------------------------------------------------------------------------
deep equal:之前写utest的时候,比较map,只能比较各长度,如今有了reflect.DeepEqual,终于能够深度比较了。
a := map[int]string{1: "hello", 2: "hi"}
b := map[int]string{2:"hi", 1:"hello"}
fmt.Println("deep equal", reflect.DeepEqual(a, b))
答案是true
----------------------------------------------------------------------------
golang的bytes包跟strings包同样强大,strings包有的方法,bytes包基本上都有额。bytes.Join, bytes.HasPrefix, bytes.LastIndex, bytes.Split……跪拜了。