golang * and &
In Golang, the * and & operators are used for pointers.
Example:
package main
import "fmt"
func main() {
var count = 5
var ptr = &count
fmt.Printf("count=%d\n", *ptr)
}
Example:
package main
import "fmt"
func main() {
var count = 5
fmt.Printf("count=%d\n", count)
fmt.Printf("address of count=%p\n", &count)
}
In this example, &count will give you the memory address where the variable count is stored.
when used in function params type
In function parameters, * is used to indicate that the function expects a pointer to the data type, not the actual value of the data type.
Here's an example:
package main
import "fmt"
func increment(x *int) {
*x++
}
func main() {
var count = 5
increment(&count)
fmt.Println(count) // Output: 6
}
In this example, the increment function takes a pointer to an integer. Inside the function, *x++ increments the value at the memory address x points to.
On the other hand, & is used in the function call (not in the function parameter type) to pass the address of the variable to the function, because the function expects a pointer.
If you tried to pass count (not &count) to increment, you'd get a compile error, because increment expects an *int (a pointer to an integer), not an int.
So in function parameter types, * indicates the function expects a pointer, and & is used in function calls to pass a pointer to a function that expects one.