Go Language Interface

Source: Internet
Author: User

Go Language Interface

The Go language provides another type of data interface, which defines all the common methods, and any other type implements this interface as long as it implements these methods.

Instance
1 /*Defining Interfaces*/2Type Interface_nameInterface {3 method_name1 [Return_type]4 method_name2 [Return_type]5 Method_name3 [Return_type]6    ...7 method_namen [Return_type]8 }9 Ten /*Define structure Body*/ OneType Struct_namestruct { A    /*variables*/ - } -  the /*Implementing interface Methods*/ - func (struct_name_variable struct_name) method_name1 () [Return_type] { -    /*Method Implementation*/ - } + ... - func (struct_name_variable struct_name) method_namen () [Return_type] { +    /*Method Implementation*/ A}
Instance
1 Package Main2 3 Import (4     "FMT"5 )6 7Type PhoneInterface {8 Call ()9 }Ten  OneType Nokiaphonestruct { A } -  - func (Nokiaphone nokiaphone) call () { theFmt. Println ("I am Nokia, I can call you!") - } -  -Type IPhonestruct { + } -  + func (iphone iphone) call () { AFmt. Println ("I am iPhone, I can call you!") at } -  - Func Main () { -     varPhone Phone -  -Phone =New(Nokiaphone) in Phone.call () -  toPhone =New(IPhone) + Phone.call () -  the}

In the example above, we define an interface phone with a method call () inside the interface. Then we define a phone type variable in the main function and assign it to Nokiaphone and iphone, respectively. The call () method is then called and the output is as follows:

I am Nokia, I can call you! I am iPhone, I cancall you!

Go Language Interface

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.