Preliminary interpretation of interface-related writing methods in Golang

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

Preliminary interpretation of interface-related writing methods in Golang


Overview
If Goroutine and channel are the two cornerstones of go concurrency, then the interface is the key to the data type in the Go language programming. In the real programming of the go language, almost all data structures are expanded around the interface, which is the core of all the data structures in the go language.
The interface in the Go language is a collection of methods (method set) that specifies the behavior of the object: if it (any data type) can do these things, then it can be used here.

Definition and use of interfaces

Like what


Copy the Code code as follows:


Type I interface{
Listen and hear Get () int
Listen and listen Put (int)
Hear
}




This passage defines an interface that contains two functions get and put


Well, one of my interfaces implements this interface:


Copy the Code code as follows:


Type S struct {val int}
Func (this *s) Get int {
Listen and listen to return This.val
}
Func (this *s) Put (v int) {
Listen and hear this.val = V
Hear
}




The structure S is the implementation of the interface I


The notation of interface in Go

Here are some examples of interface:


Copy the Code code as follows:



Func SomeFunction (w interface{write (String)}) {
Listen and listen to W.write ("pizza")
Hear
}



In this example, the interface is defined directly in the parameters, very special ...



Copy the Code code as follows:


Func weirdfunc (i int) interface{} {
Listen if i = = Listen 0 {
Listen and hear return "zero"
Hear
Listen to return i;
}




Interface Assignment Value
We can assign an object instance that implements an interface to an interface or assign another interface to an interface.


(1) Assigning values through object instances

Before assigning an object instance to an interface, ensure that the object implements all the methods of the interface. Consider the following example:


Copy the Code code as follows:


Type Integer int
Func (a integer) less (b integer) bool {
Listen to return a < b
}
Func (a *integer) Add (b Integer) {
Listen *a + = b
}


Type Lessadder Interface {Listen
Listen less (b Integer) bool Listen
Listen to add (b Integer)
}

var a Integer = 1
var B1 lessadder = &a//ok
var b2 lessadder = a listen to//not OK



B2 's assignment will report a compilation error, why? Remember the rules of the go language discussed in the < Type method > chapter?


The method set of any other named type T consists of all methods with receiver type T. The method set of the corresponding pointer type T is the set of any methods with receiver T or T (so is, it also contai NS The method set of T).
That is to say, *integer implements all the methods of interface Lessadder, and integer only implements the less method, so it cannot be assigned a value.

(2) assigning values via interfaces


Copy the Code code as follows:



Listen and listen and listen to the Var R io. Reader = new (OS. File)
Listen and listen and listen to the Var rw io. Readwriter = R Listen//not OK

Listen and listen and listen to the Var rw2 io. Readwriter = new (OS. File)
Listen and listen and listen to the Var R2 io. Reader = Rw2 Listen to listen to//ok



Because R does not have a write method, it cannot be assigned to RW.


Interface nesting
Let's take a look at another interface in the IO package:


Copy the Code code as follows:



Readwriter is the interface that groups the basic Read and Write methods.
Type Readwriter Interface {
Listen to reader
Listen to writer
}



The interface is nested with IO. Reader and Io.writer two interfaces, in fact, it is equivalent to the following:



Copy the Code code as follows:



Type Readwriter Interface {
Read (P []byte) (n int, err error) listen
Write (P []byte) (n int, err error)
}



Note that the interface in the go language cannot be nested recursively,



Copy the Code code as follows:



Illegal:bad cannot embed itself
Type Bad Interface {
Listen bad
}

ILLEGAL:BAD1 cannot embed itself using Bad2
Type Bad1 Interface {
Listen to Bad2
}
Type Bad2 Interface {
Listen to Bad1
}




Null interface (Empty interface)
The null interface is special, and it does not contain any methods:


Copy the Code code as follows:

interface{}


In the go language, all other data types implement an empty interface.



Copy the Code code as follows:



var v1 interface{} = 1
var v2 interface{} = "abc"
var v3 interface{} = struct{X int}{1}



If the function intends to receive any data type, the reference can be declared as interface{}. The most typical example is the functions of the print and Fprint series in the standard library FMT package:



Copy the Code code as follows:



Func fprint (w io. Writer, a ... interface{}) (n int, err error) listen
Func fprintf (w io. Writer, format string, a ... interface{})
Func fprintln (w io. Writer, a ... interface{})
Func Print (A ... interface{}) (n int, err error)
Func Printf (format string, a ... interface{})
Func Println (A ... interface{}) (n int, err error)



Note that []t cannot be assigned directly to []interface{}



Copy the Code code as follows:



Listen, listen and listen t: = []int{1, 2, 3, 4}
Listen and listen and listen to the Var s []interface{} = t



The following error is printed at compile time:


Cannot use T (Type []int) as type []interface {} in Assignment

We must do this in the following way:


Copy the Code code as follows:



T: = []int{1, 2, 3, 4}
S: = Make ([]interface{}, Len (t))
For I, V: = Range T {
Listen to listen to s[i] = V
}


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.