Created
April 30, 2015 10:57
-
-
Save insanity54/c99921bebde702557b8f to your computer and use it in GitHub Desktop.
why do they do `p=new(int)`?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
func learnMemory() (p, q *int) { | |
// Named return values p and q have type pointer to int. | |
p = new(int) // Built-in function new allocates memory. | |
// The allocated int is initialized to 0, p is no longer nil. | |
s := make([]int, 20) // Allocate 20 ints as a single block of memory. | |
s[3] = 7 // Assign one of them. | |
r := -2 // Declare another local variable. | |
return &s[3], &r // & takes the address of an object. | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment