mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-06 14:56:54 +02:00
Merge pull request #3848 from petrroll/patch-1
[go/en] Clarify safety of taking local variable address.
This commit is contained in:
@@ -168,10 +168,11 @@ func learnNamedReturns(x, y int) (z int) {
|
|||||||
|
|
||||||
// Go is fully garbage collected. It has pointers but no pointer arithmetic.
|
// Go is fully garbage collected. It has pointers but no pointer arithmetic.
|
||||||
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
|
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
|
||||||
|
// Unlike in C/Cpp taking and returning an address of a local varible is also safe.
|
||||||
func learnMemory() (p, q *int) {
|
func learnMemory() (p, q *int) {
|
||||||
// Named return values p and q have type pointer to int.
|
// Named return values p and q have type pointer to int.
|
||||||
p = new(int) // Built-in function new allocates memory.
|
p = new(int) // Built-in function new allocates memory.
|
||||||
// The allocated int is initialized to 0, p is no longer nil.
|
// The allocated int slice is initialized to 0, p is no longer nil.
|
||||||
s := make([]int, 20) // Allocate 20 ints as a single block of memory.
|
s := make([]int, 20) // Allocate 20 ints as a single block of memory.
|
||||||
s[3] = 7 // Assign one of them.
|
s[3] = 7 // Assign one of them.
|
||||||
r := -2 // Declare another local variable.
|
r := -2 // Declare another local variable.
|
||||||
|
Reference in New Issue
Block a user