聊聊关于Go Type的使用场景

发布时间:2022-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了聊聊关于Go Type的使用场景脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
本文由go语言教程栏目给大家介绍关于Go TyPE的使用场景 ,希望对需要的朋友有所帮助!

Go Type 使用场景@H_304_3@

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的使用场景的详细内容,更多请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的聊聊关于Go Type的使用场景全部内容,希望文章能够帮你解决聊聊关于Go Type的使用场景所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。