本文由go語言教程欄目給大家介紹關(guān)于Go Type的使用場景 ,希望對需要的朋友有所幫助!
Go Type 使用場景
type 使用場景
1. 定義結(jié)構(gòu)體
// 定義商標(biāo)結(jié)構(gòu) //將Brand定義為如下的結(jié)構(gòu)體類型 type Brand struct { } // 為商標(biāo)結(jié)構(gòu)添加Show()方法 func (t Brand) Show() { }
2. 作別名
在 Go 1.9 版本之前定義內(nèi)建類型的代碼是這樣寫的:
type byte uint8 type rune int32
而在 Go 1.9 版本之后變?yōu)椋?/p>
type byte = uint8 type rune = int32
區(qū)分類型別名與類型定義
// 將NewInt定義為int類型 type NewInt int // 將int取一個別名叫IntAlias type IntAlias = int func main() { // 將a聲明為NewInt類型 var a NewInt // 查看a的類型名 fmt.Printf("a type: %Tn", a) // 將a2聲明為IntAlias類型 var a2 IntAlias // 查看a2的類型名 fmt.Printf("a2 type: %Tn", a2) } a type: main.NewInt a2 type: int
批量定義結(jié)構(gòu)體
type ( // A PrivateKeyConf is a private key config. PrivateKeyConf struct { Fingerprint string KeyFile string } // A SignatureConf is a signature config. SignatureConf struct { Strict bool `json:",default=false"` Expiry time.Duration `json:",default=1h"` PrivateKeys []PrivateKeyConf } )
單個定義結(jié)構(gòu)體
type PrivateKeyConf struct { Fingerprint string KeyFile string } type SignatureConf struct { Strict bool `json:",default=false"` Expiry time.Duration `json:",default=1h"` PrivateKeys []PrivateKeyConf }