In Go, address operators are used to obtain the memory address of a variable. This allows the programmer to manipulate the contents of the variable directly in memory. The two address operators in Go are the ampersand operator (&) and the asterisk operator (*).
The ampersand operator is used to obtain the memory address of a variable. For example, given a variable x, the expression &x returns the memory address of x. This memory address can be stored in a pointer variable using the appropriate data type.
The asterisk operator is used to access the value stored at a particular memory address. This is known as de-referencing a pointer. For example, given a pointer variable p, the expression *p returns the value stored at the memory address pointed to by p.
Practice Questions on Address operators in Golang
Here are some practice questions on address operators in Go:
What is the memory address of variable x in the following code snippet?
x := 42
p := &x
A. 0x0012
B. 0x0024
C. 0x0048
D. 0x0080
Answer: B
What is the value of variable x after executing the following code snippet?
x := 42
p := &x
*p = 10
A. 10
B. 32
C. 42
D. 52
Answer: A
Which of the following expressions correctly declares a pointer variable to a float64 value?
A. var p *float64 = &3.14
B. var p *float64 = 3.14
C. var p float64 = &3.14
D. var p float64 = *3.14
Answer: A
What is the value of variable y after executing the following code snippet?
x := 42
p := &x
y := *p
A. 0
B. 10
C. 42
D. 52
Answer: C
Which of the following expressions correctly assigns a new value to the memory location pointed to by p?
A. p = 10
B. p = 10 C. &p = 10 D. &p = 10
Answer: B