首頁 > 後端開發 > Golang > 主體

聊聊關於Go Type的使用場景

藏色散人
發布: 2021-10-26 17:07:01
轉載
2451 人瀏覽過

本文由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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!