Embedding and inheritance of Golang

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

Listen, Golang does not support inheritance, only embedding and aggregation are supported (anonymous fields are called embedding, with name segments called aggregations). Golang is embedded to achieve similar inheritance effects and is more concise.

Listen to an example

Type listen to struct{listen to listen b listen int} Listen to Func listen (Base listen *base) listen to SETB (i listen int) Listen {Listen to listen to hear base.b listen = Listen to base.b listen + listen i} Listen to the type listen derive listen to the struct listen { Listen to listen to listen to the embed listen to listen to listening to hear the D listen to listen to hear the int listen//listen to Aggregation} Listen to Func (Derive listen to the int) listen to the setd (I listen to int.) Hear {Listen to hear derive.d listen = Listen to DERIVE.D listen + Listen I Listen to the Func hear main () Listen {Listen to hear the Var listen d listen to derive listen to listen to Fmt.println (D.B, listen to D.D) listen to listen to listen to the D.SETB (5) Listen to the D.SETD (10) Listen to hear and listen to the FMT. Println (D.B, listen D.D)}

Run results

when a type is embedded in a custom type, any method in the embedded type can be called as a method of the custom struct itself. For example , if you embed basein Derive , any data members and methods of base can be treated as Derive its own data members and method calls. From a practical perspective, embedding in Golang is similar to inheritance in C + + .


This article from "Talking Cabbage" blog, declined reprint!

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.