Golang Structural Body

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

First, struct declaration and initialization:

/*声明结构体*/type person struct {    name string    age  int}/*初始化结构体,并赋给变量 per*/per := person {name : "eagle", age : 24}

Ii. Anonymous struct declaration and initialization

per := struct {    name string    age  int}{    name : "eagle", age : 24,}/*备注:  (1) 匿名结构体的初始化和声明必须合并,不能拆分开  (2) 这里的最后一个逗号(,)必须要有,否则会报错*/

Third, struct anonymous member declaration and initialization

/*声明结构体*/type person struct{    string    int}/*初始化结构体,并赋给变量 per*/per := person {name : "eagle", age : 24}/*备注:结构体内部限制成员类型不能相同,即type person struct{    string    int}per := person {"eagle", “guangdong", 24}会抛出“duplicate field string”异常信息,GO语言系统不会聪明地认为第一个成员和第二个成员都是string类型,第三个成员是int类型*/

Iv. structure Nesting

/*声明结构体*/type person struct {    name string    age  int}type man struct {    sex  string    person}/*初始化结构体,并赋给变量 man*/man := person {sex : "男", person : person {name : "eagle", age : 24}}

V. Structural methods

import "fmt"/*声明结构体*/type person struct{    name string    age  int}/*判断两个人是否名字相同,值传递,返回值为 bool*/func (per person) IsEqual(anoPer person) bool {    anoPer.name = "john"    return per.name == anoPer.name}/*交换两个人名字,引用传递,无返回值*/func swap(per* person, anoPer* person) {    anoPer.name, per.name = per.name, anoPer.name}func main() {/*初始化结构体,并赋给变量 per*/perOne := person {name : "eagle", age : 24}perTwo := person {name : "john", age : 24}fmt.Println("PerOne:" + perOne.name)swap(&perOne, &perTwo)fmt.Println("PerOne:" + perOne.name)}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.