This article is provided by the go language tutorial column to introduce you to the usage scenarios of Go Type. I hope it will be helpful to friends in need!
Go Type Usage Scenario
type Usage Scenario
1. Define the structure
// 定义商标结构 //将Brand定义为如下的结构体类型 type Brand struct { } // 为商标结构添加Show()方法 func (t Brand) Show() { }
2. Make an alias
Before the Go 1.9 version, the code to define the built-in type was written like this:
type byte uint8 type rune int32
And after the Go 1.9 version it became:
type byte = uint8 type rune = int32
Distinguish between type aliases and type definitions
// 将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
Batch definition structure
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 } )
Single definition structure
type PrivateKeyConf struct { Fingerprint string KeyFile string } type SignatureConf struct { Strict bool `json:",default=false"` Expiry time.Duration `json:",default=1h"` PrivateKeys []PrivateKeyConf }
The above is the detailed content of Let's talk about the usage scenarios of Go Type. For more information, please follow other related articles on the PHP Chinese website!