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……跪拜了。