Golang Learning: Interface replication and interface query

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
package main import  "FMT" Type ifile interface {read () Write ()}type IReader  interface {read ()}type file struct {}func  (f *file)  Read ()  {} func  (F *file)  write ()  {}func main ()  {f := new (File) var f1  ifile = f  // ok  because file implements all the methods in IFile VAR F2 IREADER = F1  // ok  because IFile contains all the methods in Ireader// var f3 ifile = f2     // error  because Ireader does not meet ifile (less one method)// var f3 ireader = new (File)//  ok  because file implements all the methods in Ireader// var f4 ifile = f3           // error  because Ireader does not meet ifile  ibid. How to solve it?   to query the//  interface query with an interface//  this if statement checks if the object instance that the File1 interface points to implements the IFile interface//  executes the specific code if//  is implemented.   NOTE: The emphasis here is on object instances, that is, the new (File)// file contains all the methods in IFile//  so ok = trueif f5, ok := f3. (IFile);  ok {fmt. Println (F5)}//  asks the interface whether the object it points to is a type//  The IF statement determines whether the object instance that the File1 interface points to is *file type//  still Okif f6, ok  := f3. (*file);  ok {fmt. Println (f6)}fmt. Println (F1, F2, F3)}


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.