We ended the previous chapter with a warning about the
downsides of the reflection interface.
That warning applies with even more force to
the unsafe
package described in this chapter.
High-level languages insulate programs and programmers not only from the arcane specifics of individual computer instruction sets, but from dependence on irrelevancies like where in memory a variable lives, how big a data type is, the details of structure layout, and a host of other implementation details. Because of that insulating layer, it’s possible to write programs that are safe and robust and that will run on any operating system without change.
The unsafe
package lets programmers reach through the
insulation to use some crucial but otherwise inaccessible
feature, or perhaps to achieve higher performance.
The cost is usually to portability and safety, so one
uses unsafe
at one’s peril.
Our advice on how and when to use unsafe
parallels Knuth’s
comments on premature optimization, which we quoted in Section 11.5.
Most programmers will never need to use unsafe
at all.
Nevertheless, there will occasionally be situations where some critical
piece of code can be best written using unsafe
.
If careful study and measurement indicates that unsafe
really is
the best approach, restrict it to as small a region as possible, so that
most of the program is oblivious to its use.
For now, put the last two chapters in the back of your mind.
Write some substantial Go programs.
Avoid reflect
and
unsafe
; come back to these chapters only if you must.
Meanwhile, happy Go programming. We hope you enjoy writing Go as much as we do.
3.21.76.0