首頁  >  文章  >  後端開發  >  聊聊關於Go Type的使用場景

聊聊關於Go Type的使用場景

藏色散人
藏色散人轉載
2021-10-26 17:07:012460瀏覽

本文由go語言教學專欄為大家介紹關於Go Type的使用場景 ,希望對需要的朋友有幫助!

Go Type 使用場景

type 使用場景

#1. 定義結構體

// 定义商标结构
//将Brand定义为如下的结构体类型
type Brand struct {
}
// 为商标结构添加Show()方法
func (t Brand) Show() {
}

2. 作別名

在Go 1.9 版本之前定義內建類型的程式碼是這樣寫的:

type byte uint8
type rune int32

而在Go 1.9 版本之後變成:

type byte = uint8
type rune = int32

區分型別別名與型別定義

// 将NewInt定义为int类型
type NewInt int
// 将int取一个别名叫IntAlias
type IntAlias = int
func main() {
    // 将a声明为NewInt类型
    var a NewInt
    // 查看a的类型名
    fmt.Printf("a type: %T\n", a)
    // 将a2声明为IntAlias类型
    var a2 IntAlias
    // 查看a2的类型名
    fmt.Printf("a2 type: %T\n", a2)
}
a type: main.NewInt
a2 type: int

批次定義結構體

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
    }
)

單一定義結構體

type PrivateKeyConf struct {
    Fingerprint string
    KeyFile     string
}
type SignatureConf struct {
    Strict      bool          `json:",default=false"`
    Expiry      time.Duration `json:",default=1h"`
    PrivateKeys []PrivateKeyConf
}

以上是聊聊關於Go Type的使用場景的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除