Watershed Golang into the pit series

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

The third type of opening language is a bit negative, so it is not posted here. Interested in themselves can go to see https://andy-zhangtao.gitbooks.io/golang/content/. Anger and anger. After reading it, don't take it seriously. Just take the following things seriously.

Don't look at the content, just look at the title and thought it was a novel. If one day on the whim, maybe write a novel. But since joining a friend's marriage, it has been hit. Also into the 30-year-old, some students have been years into the million, Qianhuhouyong. But he will write some "parallel" code, there is no longer. Feeling a lot, or feel that they are not a piece can rely on writing code rich material. So it will be a matter of effort to consider how to realize technology monetization. But the series will still be finished and will not run out. So this section is named: Watershed. (Here for Cnblogs Xiha implanted Yang students send a letter of praise, the classmate bold message said the third type of write some negative, I looked at the third style, indeed some negative. So learn the lesson, write good is the king, my article I am the boss! Thanks again Xiha implanted Yang classmate)

If you don't have a C + + language experience, it's very rare to use pointers, a noun that you'll often hear in your career, but rarely used. Especially when to use *, when to use &, only by rote hard to ingenious. In Golang, the use of pointers has become a bit simpler. As explained in the previous sections of the function arguments, it is mentioned that the Golang parameter is the value pass by default, but sometimes a pointer can be used to achieve the function of reference passing. And this is just a pointer to a usage scenario in Golang, this section will talk about how pointers are used in Golang.

As mentioned earlier, each variable in the Golang is a memory location, each memory location has its defined address and can be accessed using the & operator, which represents the address in memory. For example, the following example:

var a int = 10   fmt.Printf("%x\n", &a )

By &a, the memory address of a is output. The address of each output may or may not be the same. This depends on the state of memory usage at that time. If the memory resources are not tight, Golang GC will not reclaim this memory, the output is the same piece of address. If the memory is tight, the GC reclaims the garbage memory and then allocates a chunk of memory at runtime, then outputs a new address.

In a university or other tutorial, you should mention what pointers are. For a vulgar end, here again: The pointer is a variable, the memory address is saved. As with any variable or constant, you must declare a pointer (a variable) before you can use it to store any memory address. You can declare pointer variables by using the following syntax:

var name *type

Type refers to the data type, and name is the name of the pointer. * Cannot be lost, indicating that this is a pointer-type variable. If there is no *, it becomes a normal data variable. such as declaring an int type, is this:

var i int

While declaring a pointer of type int, it is:

var i *int

Because the pointer holds the memory address, it is the same length, which is a 16-digit long number that represents the memory address. The only difference between pointers to different data types is the type of data held by the memory that the pointer points to. For example: Every home key is the same (is the same number of security doors), but each house inside the type is strange. In this, the key is the pointer, and the apartment is the data type. We can say that a key refers to the two bedroom, while the B key refers to four-bedroom.

After you declare the pointer type, you are ready to use the pointer. So, here's how to use pointers.

Use the pointer kick:

    1. Declares a pointer.
    2. Assign the memory address of the real data to this pointer
    3. Remove the memory address stored by the pointer and then fetch the data from that address.

The use of pointers is basically the kick. Instead, the value operation depends on * and &. For example:

package mainimport "fmt"func main() {   var a int = 20      var ip *int         ip = &a     fmt.Printf("Address of a variable: %x\n", &a  )   fmt.Printf("Address stored in ip variable: %x\n", ip )   fmt.Printf("Value of *ip variable: %d\n", *ip )}
var a int = 20

Declares an ordinary variable of type int and puts 20 into it.

Then the first axe (declaration pointer) Var IP *int. Declares a pointer to be used to hold a variable of type int. (The memory address length is the same, but Golang is a strongly typed language, so you must tell the compiler what type of data you are going to save, so declare it as *int)

Then chop the second axe and give the address of a to the IP. Remove the memory address of a through &a, then IP = &a the address to the IP.

Finally kick, take out the address inside the data, that is, the last printf inside the *ip. There, it's a corner. If the IP is used directly, it is actually to print the data saved by the IP (think if i=1, direct output I, is how much?) )。 The address itself is useless, and what we need is the data for the address (like the thief doesn't care about the key, but the key is to open the door). So through the *IP, directly take out the data stored in the IP address.

If you're going around, think of yourself as a thief (don't really go). Give you a key, you do not heart. And if I tell you this key can open that door, this time is the most exciting. So the IP holds the key, and *ip is the one that tells you it's the door.

Now that the key has been mentioned, go on. The key master has a blank set of keys, and the jargon is a null pointer. A null pointer is also a pointer variable type, except that no address is saved. Think of the blank key, the door can not open.

When the first axe is started (var IP *int), it is actually a null pointer. At this point the default value is 0. Of the vast majority of operating systems, 0 is a magical number, between heaven and hell. So the operating system does not allow users to directly access the 0 address (in fact, the operating system is not confident users, worry about users blind trouble). In the Golang, a special name for the null pointer, called NIL. For example, the following:

if(ptr != nil){ ... 不是空指针 }     if(ptr == nil){ ... 是空指针 }

If you can skillfully recite the pointer kick, then you will master 50%. If not .... Re-goto line1, then loop. Below begins the remaining 50% of the pointer Dafa.

The application of pointers in arrays

Don't be nervous, don't look at the pointer, it feels like a blind date. The pointer is much easier to deal with than the sister. Sister's world is Taijiquan, falsehoods, boxing without an infinitive. Against sister, like the Holy Warrior, the same moves can not be used two times (is not the car Tasaki Tanaka also inspired by the sister). and Golang Dafa, strokes style, are written very clearly. Let's look at how normal arrays work:

   a := []int{10,100,200}   var i int   for i = 0; i < MAX; i++ {      fmt.Printf("Value of a[%d] = %d\n", i, a[i] )   }

Initialize three values, then remove them in turn. Change it and blend the hands in.

   const MAX int = 3   a := []int{10,100,200}   var i int   var ptr [MAX]*int;   for  i = 0; i < MAX; i++ {      ptr[i] = &a[i] /* assign the address of integer. */   }   for  i = 0; i < MAX; i++ {      fmt.Printf("Value of a[%d] = %d\n", i,*ptr[i] )   }

Arrays of pointers are used exactly the same as other arrays. How to use it before, how to use it now. The only change is that the previous array holds the number, and now the pointer data holds the address. Beyond that, there is no difference. Two examples a contrast is enough, nothing to say.

Pointer to pointers

This scenario has to be said. You can not use it, but in case you see it, you can't know it. To tell the truth, using this big trick, nine out of ten is from C + + turned around. Can't say bad, personal habits. I do not like to use, after all, to consider the readability of the code. (Learn to be good, in order not to find scold, I personally do not like it.) Throat )

Pointer, the term is called the pointer chain. A listening chain, it indicates that there are at least two pointers. Call it a-pin, B-stitch. A pin according to the kick rules, save is the address of a data. and the B-pin holds the address of the A-pin. Around? See below:

B --> A --> Data

Assuming that the address of data is 123, the data stored in a is 123. At the same time a own address is ABC, then the data that B holds is ABC. If there is a C, then save the address of B, you are happy, you can follow a group behind.

So at this moment, the problem comes. I know a can be declared as Var a *int. What about B? *int? It seems wrong.

Take a breath and calm yourself. Think about the data type of the pointer. int is a data type, *int is a pointer type. Then a pointer to save the pointer type, that is, overlay a *int chant. So B becomes:

var b **int

If there is a C, write your own code and try it. Pointer chain that's all you need to be aware of, if you still don't understand, hand tap the following code to run:

package mainimport "fmt"func main() {   var a int   var ptr *int   var pptr **int   a = 3000   ptr = &a   pptr = &ptr   fmt.Printf("Value of a = %d\n", a )   fmt.Printf("Value available at *ptr = %d\n", *ptr )   fmt.Printf("Value available at **pptr = %d\n", **pptr)}

Hold on, it's already 99%. After reading the following, the progress bar ran to 100% (not like x ray, card you 99%).

The use of pointers in function parameters

Here just to get together that 1%, actually content already in: two < Vimi > section, mentioned. It is fine to see whether the parameter is to be passed by value or by reference.

Finally can not help, to some nonsense words. The pursuit of knowledge is understandable, but in the real world, money is the only standard for success. So in the process of learning, we should always consider how to rely on knowledge to become cash. No one read the book, equal to the toilet paper. The knowledge that cannot be turned into is equal to the study of whiteness. If you have a good idea, or if you are bored, please email me (ztao8607@gmail.com), the spark will burst in between the nonsense.

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.