Go 知识点(05)— 类型别名与类型定义
1. 類型別名
類型別名需要在別名和原類型之間加上賦值符號 = ,使用類型別名定義的類型與原類型等價,Go 語言內建的基本類型中就存在兩個別名類型。
byte是uint8的別名類型;rune是int32的別名類型;
類型別名定義形式如下:
type MyString = string
上面代碼表明 MyString 是 string 類型的別名類型。也就是說別名類型和源類型表示的是同一個目標,就譬如每個人的學名和乳名一樣,都表示同一個人。
定義 string 類型的別名,示例代碼:
func main() {type MyString = stringstr := "hello"a := MyString(str)b := MyString("A" + str)fmt.Printf("str type is %T\n", str)fmt.Printf("a type is %T\n", a)fmt.Printf("a == str is %t\n", a == str)fmt.Printf("b > a is %t\n", b > a)
}
輸出結果
str type is string
a type is string
a == str is true
b > a is false
定義 []string 類型的別名,示例代碼:
func main() {type MyString = stringstrs := []string{"aa", "bb", "cc"}a := []MyString(strs)fmt.Printf("strs type is %T\n", strs)fmt.Printf("a type is %T\n", a)fmt.Printf("a == nil is %t\n", a == nil)fmt.Printf("strs == nil is %t\n", strs != nil)
}
運行結果為:
strs type is []string
a type is []string
a == nil is false
strs == nil is true
從上面結果可以得出以下結論:
- 別名類型與源類型是完全相同的;
- 別名類型與源類型可以在源類型支持的條件下進行相等判斷、比較判斷、與
nil是否相等判斷等;
2. 類型定義
類型定義是定義一種新的類型,它與源類型是不一樣的。看下面代碼:
func main() {type MyString stringstr := "hello"a := MyString(str)b := MyString("A" + str)fmt.Printf("str type is %T\n", str)fmt.Printf("a type is %T\n", a)fmt.Printf("a value is %#v\n", a)fmt.Printf("b value is %#v\n", b)// fmt.Printf("a == str is %t\n", a == str)fmt.Printf("b > a is %t\n", b > a)
}
輸出結果為:
str type is string
a type is main.MyString
a value is "hello"
b value is "Ahello"
b > a is false
可以看到 MyString 類型為 main.MyString 而原有的 str 類型為 string,兩者是不同的類型,如果使用下面的判斷相等語句
fmt.Printf("a == str is %t\n", a == str)
會有編譯錯誤提示
invalid operation: a == str (mismatched types MyString and string)
說明類型不匹配。
下面代碼
func main() {type MyString stringstrs := []string{"E", "F", "G"}myStrs := []MyString(strs)fmt.Println(myStrs)
}
編譯報錯提示
cannot convert strs (type []string) to type []MyString
對于這里的類型再定義來說,string 可以被稱為 MyString2 的潛在類型。潛在類型的含義是,某個類型在本質上是哪個類型。潛在類型相同的不同類型的值之間是可以進行類型轉換的。
因此,MyString2 類型的值與 string 類型的值可以使用類型轉換表達式進行互轉。但對于集合類的類型[]MyString2 與 []string 來說這樣做卻是不合法的,因為 []MyString2 與 []string 的潛在類型不同,分別是 []MyString2 和 []string 。
另外,即使兩個不同類型的潛在類型相同,它們的值之間也不能進行判等或比較,它們的變量之間也不能賦值。
func main() {type MyString1 = stringtype MyString2 stringstr := "BCD"myStr1 := MyString1(str)myStr2 := MyString2(str)myStr1 = MyString1(myStr2)myStr2 = MyString2(myStr1)myStr1 = strmyStr2 = str// cannot use str (type string) as type MyString2 in assignmentmyStr1 = myStr2// cannot use myStr2 (type MyString2) as type string in assignmentmyStr2 = myStr1// cannot use myStr1 (type string) as type MyString2 in assignment
}
參考:
https://time.geekbang.org/column/article/13601
總結
以上是生活随笔為你收集整理的Go 知识点(05)— 类型别名与类型定义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022-2028年中国再生塑料颗粒行业
- 下一篇: 2022-2028年中国热塑性聚酯PBT