Inheritance of Golang, multiple inheritance (struct)

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

Hot code's coming in.

Package Mainimport"FMT"/*inheriting one struct into another struct, known as the difference between combinatorial anonymity and composition if a struct nested another anonymous struct, the struct can directly access the anonymous struct's method, enabling inheritance if a struct nested another "well-known" struct, So this pattern is called a combination. If a struct is nested with multiple anonymous structs, the struct can directly access multiple anonymous struct methods to achieve multiple inheritance*/type Carstruct{weightintnamestring}func (P*Car) Run () {fmt. Println ("Running")}type Bikestruct{Car Lunziint}type Trainstruct{Car}func (P*train) String ()string{str:= Fmt. Sprintf ("name=[%s] weight=[%d]", P.name, P.weight)returnStr}func Main () {vara Bike a.weight= -A.name="Bike"A.lunzi=2FMT. Println (a) a.run ()varb Train b.weight= -B.name="Train"B.run () fmt. Printf ("%s", &b)}

Exercise 2

Package Mainimport ("FMT"    " Time") Type Carstruct{Namestring Ageint}func (c*car) Set (namestring, ageint) {C.name=name C.age=Age}type Car2struct{Namestring}//Go has anonymous field attributesType Trainstruct{Car Car2 createtime time. time//count int is normal and the Go feature can be written as    int}//to the train method, T specifies the name of the accepted variable, which can be called This,t,pFunc (t *train) Set (ageint) {T.int=Age}func Main () {vartrain train train.int= - //the anonymous field is used here to write an age assignment//(&train). Set (+)Train. Car.set ("Huas", -) train. Car.name="Test" //here name must specify structFMT. PRINTLN (train)}

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.