這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
pre-declared type (預宣告類型)
golang 預設的有幾個預宣告類型:boole,num,string type. 這些預宣告類型被用來構造其他的類型。
type literal(字面量類型)
由其他預宣告類型組合而成(沒有使用type 關鍵字定義),
array,struct,pointer,slice,map,channel,function,interface
[2]int ,[ ] int , chan int , map[string] string ,* int
注意:type literal 中的struct,interface 特指匿名的類型,沒有使用type封裝,
命名類型和非命名類型
named type : 一個類型通過一個標識符標示就是命類型名字(type name)
unamed type: 一個類型是由先前已宣告類型組合構成被稱為類型字面量(type literal)
二者區別:
named type 可以有自己的methods, mehtods 是一種特殊形式的函數,該函數的第一個參數是該type的變數或指向該類型變數的指標(receiver).
unamed type:不能定義自己的method
|
type |
包括 |
特點 |
|
named type |
pre-declared
type declared new type |
可以定義自己的method |
|
unamed type |
type literal |
不可以定義自己的method |
一個特別重要的事情需要記住:pre-declared types 也是命名類型。所以:int 是named type , 但是 *int ,[]int 不是。
特別注意:我們不能直接為int 定義method
func (a int) methodname() {
}
不是因為int 是unnamed type ,而是為一個type定義方法必須在該類型的所在的package , int 的scope (範圍是)universe (全域的),int 是語言層面預聲明的,其屬於任何package,也就沒有辦法為其增加method.
package mainimport ( "fmt")func (a int) Print() { fmt.Println(a)}func main() { m := 12 a.Print()}[root@tata.domain /project/go/src/test]#go build name.go # command-line-arguments./name.go:7: cannot define new methods on non-local type int./name.go:13: undefined: a
Underlying Type 底層類型
所有type(類型)都有個underlying type(底層類型)。Pre-declared types 和type literals 的底層類型是它們自身;通過type newtype oldtype 的底層類型,是逐層遞迴向下尋找的,直到查到的oldtype 是Pre-declared types 和type literals。
|
type |
underlying type |
樣本 |
|
pre-declared type |
itself |
string 的underlying type 還是string |
|
type literal |
itself |
map[string]string的underlying type 還是map[string]string |
|
通過type定義的新類型:
type newtype oldtype |
逐層向下遞迴尋找oldtype,直到oldtype是pre-declared type 或type literal;找到的pre-declared type 或type literal就是underlying type |
type Map map[string]string
type SpecialMap Map
則:Map 和 SpecialMap 的underlying type
都是map[string]string |
另一條重要規則是:
type newtype oldtype: newtype不會從oldtype或其underlying type繼承任何methods .
有兩個特例就是:介面和組合類別型(composite type)
|
new type |
Methods SET |
|
type interface2 interface1 |
interface2 會繼承interface1的methods set |
|
type NewType struct {
InnerType
} |
NewType 會繼承InnerType的methods set |
|
其他type newtype oldtype |
newtype 不會從oldtype 或其underlying type中繼承任何方法 |
這裡表達的意思就是:一旦你定義一個新類型,你往往是想為其定義一個新的methods set
static type 靜態類型和dynamic type 動態類型
static type就是變數定義聲明是的類型,
只有interface 有動態類型
介面類型變數有dynamic type,介面的動態類型是其在運行時綁定值的類型
介面的動態類型可以在運行時發生變化,但是動態類型其必須滿足可以賦值給介面類型的條件,否則會發生panic;
非interface 的類型的dynamic type 就是其static type
static type就是變數定義聲明是的類型,介面類型變數還有個dynamic type,介面的動態類ixngshi在運行時其儲存的值的類型,介面的動態類型可以變化,但是其必須滿足可以賦值給介面類型的規則;對於非介面類型,動態類型就是靜態類型。