Preliminary interpretation of interface-related writing methods in Golang _golang

Source: Internet
Author: User
Tags bool data structures

Overview
if Goroutine and channel are the two cornerstones of go concurrency, then interfaces are key to data types in go programming. In the actual programming of go, almost all data structures are spread 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, it can be used here.

Definition and use of interfaces

Like what

Copy Code code as follows:

Type I interface{
Get () int
put (int)

}


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

Well, one of my interfaces implements this interface:

Copy Code code as follows:

Type S struct {val int}
Func (this *s) get int {
Return This.val
}
Func (this *s) put (v int) {
This.val = V

}


This structure S is the implementation of the interface I

The interface in Go

Let's look at a few interface examples:

Copy Code code as follows:

Func SomeFunction (w interface{write (String)}) {
W.write ("pizza")

}


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

Copy Code code as follows:

Func weirdfunc (i int) interface{} {
If i = = 0 {
Return "Zero"
}
return i;
}


interface Assignment
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, make sure that the object implements all the methods of the interface. Consider the following example:

Copy Code code as follows:

Type Integer int
Func (a integer) less (b integer) bool {
Return a < b
}
Func (a *integer) Add (b Integer) {
*a + b
}

Type Lessadder Interface {
Less (b Integer) bool
ADD (b Integer)
}

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


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

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

(2) Assigning value through interface

Copy Code code as follows:

var r io. Reader = new (OS. File)
var rw io. Readwriter = R//not OK

var rw2 io. Readwriter = new (OS. File)
var R2 io. Reader = Rw2//ok


Because R has no write method, it cannot be assigned to RW.

Interface nesting
let's look at another interface in IO package:

Copy Code code as follows:

Readwriter is the interface that groups the basic Read and Write methods.
Type Readwriter Interface {
Reader
Writer
}


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

Copy Code code as follows:

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


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

Copy Code code as follows:

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

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


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

Copy Code code as follows:
interface{}

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

Copy 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 print and Fprint series functions in the standard library FMT package:

Copy Code code as follows:

Func fprint (w io). Writer, a ... interface{}) (n int, err error)
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 Code code as follows:

T: = []int{1, 2, 3, 4}
var s []interface{} = t


The following error is output at compile time:

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

We have to do this in the following way:

Copy Code code as follows:

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


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.