- Go Systems Programming
- Mihalis Tsoukalos
- 321字
- 2021-07-02 18:08:03
Unsafe code
Unsafe code is Go code that bypasses the type safety and memory security of Go and requires the use of the unsafe package. You will most likely never need to use unsafe code in your Go programs but if for some strange reason you ever need to, it will probably have to do with pointers.
The example code in this subsection is saved as unsafe.go and will be presented in two parts.
The first part is as follows:
package main import ( "fmt" "unsafe" ) func main() { var value int64 = 5
var p1 = &value var p2 = (*int32)(unsafe.Pointer(p1))
You first create a new int64 variable that is named value. Then, you create a pointer to it named p1. Next, you create another pointer that points to p1. However, the p2 pointer that points to p1 is a pointer to an int32 integer, despite the fact that p1 points to an int64 variable. Although this is not permitted by Go rules, the unsafe.Pointer() function makes this possible.
The second part is as follows:
fmt.Println("*p1: ", *p1) fmt.Println("*p2: ", *p2) *p1 = 312121321321213212 fmt.Println(value) fmt.Println("*p2: ", *p2) *p1 = 31212132 fmt.Println(value) fmt.Println("*p2: ", *p2) }
Executing unsafe.go will create the following output:
$ go run unsafe.go *p1: 5 *p2: 5 312121321321213212 *p2: 606940444 31212132 *p2: 31212132
The output shows how dangerous an unsafe pointer can be. When the value of the value variable fits into an int32 memory space (5 and 31212132), then p2 works fine and shows the correct result. However, when the value variable holds a value (312121321321213212) that does not fit into an int32 memory space, then p2 shows an erroneous result (606940444), without giving you a warning or an error message.
- 軟件安全技術(shù)
- 潮流:UI設(shè)計(jì)必修課
- MySQL 8從入門(mén)到精通(視頻教學(xué)版)
- Mastering Selenium WebDriver
- JavaScript 網(wǎng)頁(yè)編程從入門(mén)到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開(kāi)發(fā)視頻大講堂)
- Nginx實(shí)戰(zhàn):基于Lua語(yǔ)言的配置、開(kāi)發(fā)與架構(gòu)詳解
- HTML5從入門(mén)到精通(第4版)
- Python High Performance Programming
- 現(xiàn)代C++編程實(shí)戰(zhàn):132個(gè)核心技巧示例(原書(shū)第2版)
- Advanced UFT 12 for Test Engineers Cookbook
- 軟件工程與UML案例解析(第三版)
- C# 7.0本質(zhì)論
- 原型設(shè)計(jì):打造成功產(chǎn)品的實(shí)用方法及實(shí)踐
- 自己動(dòng)手構(gòu)建編程語(yǔ)言:如何設(shè)計(jì)編譯器、解釋器和DSL
- Learning TypeScript