Maison  >  Article  >  développement back-end  >  Parlons des scénarios d'utilisation de Go Type

Parlons des scénarios d'utilisation de Go Type

藏色散人
藏色散人avant
2021-10-26 17:07:012460parcourir

Cet article est introduit par la colonne tutoriel go language pour présenter les scénarios d'utilisation de Go Type. J'espère qu'il sera utile aux amis dans le besoin !

Scénarios d'utilisation de Go Type

scénarios d'utilisation de type

1 Définir une structure

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

2 Créer un alias

Avant Go 1.9, le code pour définir un type intégré était écrit comme ceci :

type byte uint8
type rune int32
.

Et maintenant la version After Go 1.9, cela devient :

type byte = uint8
type rune = int32

Distinction entre les alias de type et les définitions de type

// 将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

Définition globale des structures

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

Définition unique des structures

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer