Golang Interface Notes

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

First, the concept

Interface types are abstractions and generalizations of other types of behavior, because interface types are not tied to specific implementation details, and in this abstract way we can make our functions more flexible and adaptable.

The uniqueness of the interface type in the go language is that it satisfies the implicit implementation. In other words, it is not necessary to define all the satisfied interface types for a given specific type; it is sufficient to simply have some necessary methods.

This design allows you to create a new interface type that satisfies a specific type that already exists but does not change the definition of those types, which is especially useful when the type we use comes from a package that is not under our control.

Second, the Declaration and use of the interface

Package Mainimport ("FMT") Type IcaleInterface{Sum (A, Bint)int}type Computerstruct{}func ( This*computer) Sum (A, Bint)int {    returnA +B}func ( This*computer) Print ()int{fmt. Println ("AI")}func Main () {FMT. Println (New(computer). Sum (1,2))    varIcale Icale =New(computer) fmt. Println (Icale. Sum (2,3))}

Three, NULL interface type: There is no requirement to implement its type, so we can assign any value to the Null interface type

Package Mainimport ("FMT") Func main () {varVInterface{} v=1FMT. Println (v) v="123"FMT. Println (v) v=trueFMT. Println (v) v= map[string]int{" One":1} fmt. Println (v)}
Package Mainimport ("FMT") Func main () {print (map[string]int{" One":1}) Print (func ()int{return 1}) Print (func ()int{return 1} ())}func print (ValInterface{}) {Fmt. Println (val)}
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.