- Hands-On Full Stack Development with Go
- Mina Andrawos
- 441字
- 2021-07-02 12:33:30
Pointers
The concept of pointers is simple—a pointer is a language type that represents the memory locations of your values. Pointers in Go are used everywhere, and that's because they give the programmer a lot of power over the code. For example, having access to your value in memory allows you to change the original value from different parts of your code without the need to copy your value around.
In Go, to create a pointer, you just append * in front of the data type of your value. For example, here is a pointer to an int value:
var iptr *int
As we mentioned in the previous section, the zero value of a pointer is nil. The behavior of nil is similar to null in languages like Java, that is, if you try to use a nil pointer, an error will get thrown.
Now, let's assume we have a value of type int called x:
var x int = 5
We also want a pointer to point to the address of x for later use:
var xptr = &x
The & operand here means that we want the address of x. Whenever you append the & operand before a variable, it basically means that we want to the address of that variable.
What if we have a pointer, and we want to retrieve the value that it points to? This operation is called de-referencing, and here is how we can do it:
y := *xptr
In the preceding code, we de-referenced the pointer xptr to obtain the value that it points to, and then we stored a copy of the value in a new variable called y.
What if we want to change the value that the pointer points to? We can still use de-referencing for that, and here is what this would look like:
*xptr = 4
Perfect! With this, you should have enough knowledge to use Go pointers in your code.
If you already have experience in pointers from a different programming language like C or C++, you are probably familiar with the concept of pointer arithmetic. This is when you perform arithmetic operations (like addition or subtraction) on pointers to go to different memory addresses. By default, Go does not support pointer arithmetic on vanilla pointers like the ones we described in this section. However, there is a package called unsafe that allows you to do so. The unsafe package is only there to give you the power, should you need it. However, it is highly recommended that you don't use it unless you absolutely have to.
Now, let's explore functions and closures in Go.
- 手機(jī)安全和可信應(yīng)用開發(fā)指南:TrustZone與OP-TEE技術(shù)詳解
- R語言數(shù)據(jù)可視化之美:專業(yè)圖表繪制指南
- Java程序設(shè)計(jì)與計(jì)算思維
- Building Mapping Applications with QGIS
- Silverlight魔幻銀燈
- 零基礎(chǔ)學(xué)MQL:基于EA的自動化交易編程
- WordPress Plugin Development Cookbook(Second Edition)
- Xamarin.Forms Projects
- Responsive Web Design by Example
- Jupyter數(shù)據(jù)科學(xué)實(shí)戰(zhàn)
- Nginx實(shí)戰(zhàn):基于Lua語言的配置、開發(fā)與架構(gòu)詳解
- 編程與類型系統(tǒng)
- Swift 4從零到精通iOS開發(fā)
- C# and .NET Core Test Driven Development
- Scratch趣味編程:陪孩子像搭積木一樣學(xué)編程