Golang initializing the structure of the body

Source: Internet
Author: User
Tags anonymous
There are two ways to initialize a struct in **golang: 1. Declare the key of all fields, 2. Neither declares key, but value corresponds to the order one by one defined.

Although mode 1 is cumbersome, anonymous fields may not have to be initialized when there is an anonymous field in the defined struct, and the anonymous field needs to be initialized in mode 2, otherwise the compiler will error (too few values in struct initializer).
"Subclass" in Golang can "inherit" the method defined at the previous level, which is equivalent to the overloaded concept in OOP * *

Package main

Import (
    "FMT"
)

type language []string

type human struct {
    name string
    age  int
    sex  bool
}

type programmer struct {
    human company
    string
    language
}

func (H *human) introduce () {
    fmt. PRINTLN ("Human")
}

func (P *programmer) introduce () {
    fmt. PRINTLN ("Programmer's")
}

func main () {
    //  h: = human{name: "SDA", Age:123, Sex:true}
    P: = programmer{ Human:human{name: "SDA", Age:123, Sex:true}, Company: "Iflytek"}
    p.introduce ()
    p.human.introduce ()
}

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.