Go Language Learning Notes---interface

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. The following defines a struct type with a field and two methods s code 6.1type s struct {i int}func (P *s) Get () int {return p.i}func (P *s) Put (v int) {p.i = v}
You can also define an interface type, which is simply a collection of methods. This defines an interface with two methods I:type I interface {Get () int Put (int)} is a legitimate implementation for an interface i,s because it defines the two methods required for I. Note that even if you do not explicitly define s to implement I, this is also true.
Interface Value:Example: Func f (P I) {//defines a function that accepts an interface type as a parameter fmt. Println (P.get ())//p implements the interface I, must have a get () method P.put (1) The//put () method is similar}
The variable p here holds the value of the interface type. Because s implements I, you can call the F pointer to it passing the value of type S: Var s; F (&s) Gets the address of s, not the value of S, because the method is defined on the pointer of S, see Code 6.1 above. This is not necessary-you can define the method to accept the value-but then the put method does not work as expected. In fact, it is not necessary to specify whether a type implements an interface means that go implements a pattern called duck typing. This is not purely a duck typing, because if possible the go compiler implements a static check on whether the type implements an interface. Suppose you need to know the actual type in function f. You can use type switch to get it in go. Func f (P I) {
Switch T: = P. (type) {//type judgment. Use (type) in a switch statement. Save type to variable t;
Case
*s: The actual type of//p is a pointer to S;
Case
*r: The actual type of//p is a pointer to R;
Case
S: The actual type of//p is S;
Case
R: The actual type of//p is R;
Default://Implements the other types of I.
}
}
Note: element. The (type) syntax cannot be used in any logic outside of switch, and if you want to judge a type outside of switch, use COMMA-OK.
Type judgment is not the only way to get the type at run time. To get the type at run time, you can also use "comma, OK" to determine whether an interface type implements a particular interface: if T, OK: = something. (I); OK {//For some implementations of interface I//T is its own type}

Comma-ok Assertion

The go language has a syntax that can directly determine if it is a variable of that type: value, OK = element. (t) where value is the value of the variable, OK is a bool type, element is a interface variable, and T is the type of assertion.

If the element does store a value of type T, then OK returns true, otherwise false is returned.

Example: Package Main
Import ("FMT" "StrConv")
Type Element interface{}type List [] Element
Type person struct {name string age int}
Defines the string method and implements the FMT. Stringerfunc (P person) string () string {return ' (name: "+ p.name +"-Age: "+strconv. Itoa (P.age) + "Years)"}
Func main () {list: = Make (list, 3) list[0] = 1//int list[1] = "Hello"//a string list[2] = person{"Denn Is ", 70}
For index, element: = Range List {if value, OK: = element. int); OK {fmt. Printf ("list[%d" is a int and its value is%d\n ", index, value)} else if value, OK: = element. (string); OK {fmt. Printf ("list[%d" is a string and its value is%s\n ", index, value)} else if value, OK: = element. (person); OK {fmt. Printf ("list[%d" is a person and its value is%s\n ", index, value)} else {fmt. Println ("list[%d] is of a different type", Index)}}} output: List[0] is an int and its value is 1list[1] is a stri NG and its value are hellolist[2] is a person and their value is (name:dennis-age:70 years)

Determine that a variable implements an interface that can be used: t: = something. (I)
NULL InterfaceBecause each type can match to an empty interface: interface{}. We can create a normal function that accepts an empty interface as a parameter: Listing 6.2. function with NULL interface as parameter Func g (something interface{}) int {return something. ( I). Get ()} return something in this function. (I). Get () is a bit of a trick. The value something has type interface{}, which means that the method has no constraints: it can contain any type. (I) is a type assertion that is used to convert an something to an I-type interface. If you have this type, you can call the Get () function. Therefore, if you create a new variable of type *s, you can also call G (), because *s also implements an empty interface. s = new (s) fmt. Println (g (s)); Example: Package Mainimport ("FMT") func main () {s: = new (s) ss: = "Hello World" FMT. Printf ("%d\n", g (s)) fmt. Printf ("%s\n", demo (ss))}func g (something interface{}) int {return something. (I). Get ()? why not something. (S). Get ()}func demo (Something interface{}) string {return something. ( String)}type I interface {get () int Put (int)}type S struct {I int}func (P *s) Get () int {return P.i}func (p * S) Put (v int) {p.i = v}
Output Result: 0 Hello World
Example 2:package mainimport ("FMT") func main () {s: = s{1} fmt. Printf ("%d\n", g (s))}func g (something s) int {return something. Get ()}type S struct {i int}func (P *s) Get () int {return P.i}func (P *s) Put (v int) {p.i = v}
Output Result: 1
Interface name According to the rules, the single-method interface is named method name plus-er suffix: reader,writer,formatter, etc. There are a bunch of such names that efficiently reflect their responsibilities and the names of the functions they contain. Read,write,close,flush,string and so on have a normative statement and meaning. To avoid confusion, do not let the same name be used unless there is a similar declaration and meaning. Conversely, if a type implements the same method as a well-known type, the same name and declaration are used, and the string conversion method is named string instead of ToString.

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.