interface{} Pointers

In line ABCD, which ones of them have syntax issues?

  1. package main
  2. type S struct {
  3. }
  4. func f(x interface{}) {
  5. }
  6. func g(x *interface{}) {
  7. }
  8. func main() {
  9. s := S{}
  10. p := &s
  11. f(s) //A
  12. g(s) //B
  13. f(p) //C
  14. g(p) //D
  15. }

Answer

  1. package main
  2. type S struct {
  3. }
  4. func f(x interface{}) {
  5. }
  6. func g(x *interface{}) {
  7. }
  8. func main() {
  9. s := S{}
  10. p := &s
  11. f(s) //A correct
  12. g(s) //B incorrect
  13. f(p) //C correct
  14. g(p) //D incorrect
  15. }

Temporary Pointer

Explain why the printed output of below are 333, and modify line A to assure 012 is printed.

  1. package main
  2. const N = 3
  3. func main() {
  4. m := make(map[int]*int)
  5. for i := 0; i < N; i++ {
  6. m[i] = &i //A
  7. }
  8. for _, v := range m {
  9. print(*v)
  10. }
  11. }

Answer

  1. package main
  2. const N = 3
  3. func main() {
  4. m := make(map[int]*int)
  5. for i := 0; i < N; i++ {
  6. j := int(i)
  7. m[i] = &j
  8. }
  9. for _, v := range m {
  10. print(*v)
  11. }
  12. }