Go Learning notes--types and interfaces

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

If the rest of the go language doesn't seem to be much different from the C + + language, then its interface design must be surprising, yes, sometimes it really makes me feel like I'm using a dynamic language illusion.

Structure type

Here, or the C language is very similar to the definition of structure:
Type man struct {     name string age     int}

Declaring struct variables and initialization:
var m man   //Declaration man variable m: = new (man)  //Declaration of a man pointer m: = man{name: "Jack", age:12}//Declare and initialize m: = man{"Jack",/  / Declaring and initializing

Method

The function defined by the go language is called a method, and the object-oriented term is the same. The method definition of the go language looks very avant-garde, the method is the message, so the method definition first describes the method (message) receiver, then the method name and its arguments.
Func (M *man) introduce () bool {    FMT. Println ("Name:", M.name)    return True}

The calling method uses the "." Symbol:
M: = man{"Jack", 12}ok: = M.introduce ()
Using the structure of the method, we can even like Ruby, the system in order to type a monkey patch, add a new method, but the means slightly curved, for example, the following code for the string type to add a Chomp method to remove the string last line break:
Package Mainimport ("FMT" "strings") type MyString stringfunc (str MyString) Chomp () string {return strings. TrimRight (String (str), "\ n")}func main () {str: = "Hello world!\n" MS: = MyString (str) FMT. Println (Ms.chomp ())   //Output Hello world!}


Method Agent

In fact, Google called this feature an embedded type (Embedded type), if Type A contains a type B, usually in other languages we call a has-a B, but in go we call a A is a B, because B becomes a member of A, Then we can be considered a also has the function of B, then it is a B. So what is the role of the method agent? As the name implies, we can directly invoke the method of B on a, like A.b.b_method, for example: In the Matrix, Neo is the savior, so he has (including) the ability of the Savior, so we send fly directly to the message to Neo,neo must be able to fly, The same Neo's previous generations of savior may not be called Neo but we tell him directly fly, they can fly, so the use of method agent is really simple and straightforward:
Package Mainimport "FMT" Func Main () {n: = new (Neo) n.fly ()  //output: The one can fly!} Type Neo struct{theone}type theone struct{}func (o *theone) Fly () {fmt. Println ("The One Can Fly!")}

In the Ruby language, there are many ways to do this proxy code, and the Go language embedded type of characterization and this feature is so similar to the spirit, hey, hehe. In addition, we think this embedding type and OOP inheritance is very much like, why not called the method of inheritance and proxy it? The reality is that NEO does just send the message to Theone, even if they have the same members, but the fly method can only see the Theone member variables, so called method Proxy is more appropriate, you can write code verification.

Go style Duck-type

Go-style duck type. Personally think this is the most cool place in the go language, in the static language to the dynamic language of the duck type to achieve such a coquettish.   The interface of the go language is the result of this. Interface Definition:
Type Duck Interface {     run ()     height () int     gaga (Word string)}

Only a series of method declarations are included in the Duck interface. We can then use this in the method parameter:
Func Duckrun (d Duck) {    d.run ()}

So is it true that we need to accomplish multiple duck interfaces? NO. That would not be the same as Java. The only use of the interface of the go language is to satisfy the compiler (alas, somewhat helpless), so that the compiler will check the Duckrun function entry to see if the passed in object contains the three methods contained in the Duck interface, and compile if it conforms to the definition. Isn't that the duck type?   Just checking to see if these methods are included, regardless of whether they are of a certain type, is a great way to say the duck type of Go style. For example, a person has a say way of speaking, but in fact for a function that needs say method, we can give it a Earth object, even though the earth does not say anything:
Package Mainimport "FMT" Func Main () {     m: = man{name: "Jack"} M.say () E: = new (Earch) Saysth (e) saysth (&m)  //say The receiver of the () method is a pointer variable, so here is the & Fetch address}func saysth (obj object) {Obj.say ()}type object Interface{say ()}type man Struct{name String}type earch Struct{}func (M *man) say () {FMT. Println ("Man says:i ' M", M.name)}func (e *earch) say () {//do Nothing}

Null interface and type

Empty interface (interface{}) does not contain any method, and because of this, all types implement an empty interface. The null interface does not have any effect on the description (because it does not contain any method), but the null interface is useful when we need to store any type of numeric value, because it can store any type of value. It is somewhat similar to the void* type of C language.
Define a as NULL interface var a interface{}var i int = 5s: = "Hello World"//A can store any type of numeric value A=i,a=s


A function takes interface{} as a parameter, then he can accept any type of value as a parameter, and if a function returns interface{}, it can return any type of value.
We know that interface variables can store any type of value (this type implements the interface). So how do we know what type of object is actually stored in this variable? You can use the Comma-ok assertion
Value, OK = element. T

Where value is the value of the variable, OK is a bool type, element is the 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.
In addition, when it comes to the need for type processing in the Go language, reflection is needed. The go language implements reflection, so-called reflection is the state of the dynamic runtime. The package we usually use is a reflect bag. The use of reflect is generally divided into three steps, the following brief explanation: to go to reflect is a type of value (these values are implemented in the empty interface), first need to convert it to reflect object (reflect. Type or reflect.value, calling different functions depending on the situation). The two ways to get these are:
T: = reflect. TypeOf (i)//Get the type of meta data, through t we can get all the elements inside the type definition V: = reflect. ValueOf (i)//get the actual value, through v we get the value stored in it, we can change the value


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.