Go language Basics: In-depth understanding of struct embedded Inteface

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

An in-depth understanding of the anonymous interface used in the previous article: http://blog.csdn.net/uudou/article/details/52456133
For the use of struct embedded inteface, I am research long time only understand, here record my question:

1. How to better understand the anonymous interface

// 匿名接口可以被用作变量或者结构属性类型struct {    interface {        string    }}

The above man class can be expanded into

type gender interface {        GetGender() string    }type Man struct {    gender//}

The code is more understood than it is written.

2. What is the use of anonymous interface objects, and why should they be referenced?

    // 匿名接口对象的使用    varMan := Man{&Employee{        name:   "Nobody",        age:    20,        10000,        "Unknown",    }}

The reason is that the recipient of the implementation of the anonymous interface gender is a pointer, so this is the way to assign a value by reference.

3. Why can the initialization of the man class be initialized with employee?
We know that go has a rule that if we define a interface variable, then this variable can have any type of image that implements the interface. The employee class implements the gender interface, while the members of the man have a gender interface, so man can initialize with employee.

4. Re-fill a feature
The struct of the inline interface also satisfies the basics of the go language: the inheritance and overriding attributes mentioned in method

method继承和重写继承:如果 struct 中的一个匿名段实现了一个 method,那么包含这个匿名段的 struct 也能调用该 method。重写:如果 struct 中的一个匿名段实现了一个 method,包含这个匿名段的 struct 是可以重写匿名字段的方法的。

Eighth section structure and interface
embedded in Golang (embeded)

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.