本文由go语言教程栏目给大家介绍关于go type的使用场景 ,希望对需要的朋友有所帮助!
go type 使用场景
type 使用场景
1. 定义结构体
// 定义商标结构//将brand定义为如下的结构体类型type brand struct {}// 为商标结构添加show()方法func (t brand) show() {}
2. 作别名
在 go 1.9 版本之前定义内建类型的代码是这样写的:
type byte uint8type rune int32
而在 go 1.9 版本之后变为:
type byte = uint8type rune = int32
区分类型别名与类型定义
// 将newint定义为int类型type newint int// 将int取一个别名叫intaliastype intalias = intfunc 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.newinta2 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的使用场景的详细内容。