Go language struct

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

First, the definition of struct structure:

Type person struct {name stringage  int}

This defines the person structure, name is the string type name, and age is an int type.

Second, declare a struct variable:

var p person

Three, the assignment value:

There are three ways to do this, respectively:

1, directly assigned value

P.name = "Xiaoming" P.age = 12

2. Initialize values in sequence

Tom: = person{"Tom", 20}

3, through the way of field:value initialization, so that the order can be arbitrary

John: = person{age:21, Name: "John"}

Iv. Anonymous fields for structs

Go support provides only field types, and does not provide a way to declare field names. That is, an anonymous field, also called an embedded field. (Can be understood by inheritance in Java)

When an anonymous field is a struct (or other custom type), all the fields owned by the struct are implicitly introduced into the currently defined struct.

As an example:

Type Human struct{    name string age    int}type Student struct{    Human//anonymous field, then Student has all the fields    of Human Score Int}func Main () {    var xiaoming = student{human{"Xiaoming", +}, 98}    FMT. Println (xiaoming.    Human.name); Fmt. Println (xiaoming.    Human.age); Fmt. Println (Xiaoming.score);}



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.