3. Go - Pointer Basics
Pointer is a reference to a memory, or an address to something saved in memory.
Could use pointers to reference big data stored in memory to save time and efficiency. Could also use pointers to change values outside of scopes.
Example Code:
// creating a variable that returns a pointer
package main
import "fmt"
var pointervar *int // This is a pointer type with int
func main() {
variable := "string"
intvar := 50
pointervar = &intvar
var x int = MathAdd(&variable)
fmt.Println(variable)
fmt.Println(x)
fmt.Println(*pointervar)
}
func MathAdd(p *string) int {
*p = "toy"
return 5
}
* = pointer to a type/variable, the value that is stored at address
& = address of a type/variable where its stored
*& = dereference the value stored at the address
var b = new(int)
// this creates a variable integer that also returns a pointer. can reference pointer b with "&b"
Dereferencing Pointer Slices:
// must dereference the slice type first with (*VARIABLE)
// then can access indexs
Example:
package main
import "fmt"
type myArray []int
func (list *myArray) removeValue(x int) {
for i := 0; i < len(*list); i++ {
fmt.Println(i)
if (*list)[i] == x {
*list = append((*list)[:i], (*list)[(i+1):]...)
return
}
}
}
func main() {
x := myArray{1, 2, 3, 4, 5}
fmt.Println(x)
x.removeValue(2)
fmt.Println(x)
}
Comments
Post a Comment