Consider this Go program that modifies a variable through a pointer parameter. What will it print?
package main import "fmt" func modify(x *int) { *x = *x + 10 } func main() { a := 5 modify(&a) fmt.Println(a) }
Think about what happens when you change the value at the memory address the pointer points to.
The function modify receives a pointer to a. It adds 10 to the value at that address. So a becomes 15.
Look at this Go code that changes a struct field via a pointer. What is printed?
package main import "fmt" type Point struct { x int y int } func move(p *Point) { p.x = 10 p.y = 20 } func main() { pt := Point{1, 2} move(&pt) fmt.Println(pt.x, pt.y) }
Remember that pointers to structs allow modifying the original struct fields.
The move function changes the fields of the struct via the pointer. So the original struct's fields become 10 and 20.
Examine this Go code. The function tries to change the value of num but it does not work. Why?
package main import "fmt" func changeValue(x int) { x = 100 } func main() { num := 50 changeValue(num) fmt.Println(num) }
Think about how Go passes arguments to functions by default.
In Go, function parameters are passed by value. So changeValue gets a copy of num. Changing x inside the function does not affect num.
Choose the correct Go function signature that accepts a pointer to an int.
In Go, the pointer symbol * goes before the type, not the variable name.
The correct syntax is func update(x *int). The pointer symbol * is before the type int. Other options are invalid syntax.
Consider this Go code that appends to a slice via a pointer. How many elements does the slice have after calling appendValue?
package main import "fmt" func appendValue(s *[]int, v int) { *s = append(*s, v) } func main() { nums := []int{1, 2, 3} appendValue(&nums, 4) fmt.Println(len(nums)) }
Appending to a slice inside a function requires updating the original slice via pointer.
The function appends 4 to the slice by dereferencing the pointer and assigning the new slice back. So the slice length becomes 4.