interface{} Pointers
In line ABCD, which ones of them have syntax issues?
package main
type S struct {
}
func f(x interface{}) {
}
func g(x *interface{}) {
}
func main() {
s := S{}
p := &s
f(s) //A
g(s) //B
f(p) //C
g(p) //D
}
Answer
package main
type S struct {
}
func f(x interface{}) {
}
func g(x *interface{}) {
}
func main() {
s := S{}
p := &s
f(s) //A correct
g(s) //B incorrect
f(p) //C correct
g(p) //D incorrect
}
Temporary Pointer
Explain why the printed output of below are 333, and modify line A to assure 012 is printed.
package main
const N = 3
func main() {
m := make(map[int]*int)
for i := 0; i < N; i++ {
m[i] = &i //A
}
for _, v := range m {
print(*v)
}
}
Answer
package main
const N = 3
func main() {
m := make(map[int]*int)
for i := 0; i < N; i++ {
j := int(i)
m[i] = &j
}
for _, v := range m {
print(*v)
}
}