0

The library that I'm using to work with DB provides convenient interface to save/load data without casting

Put(c context.Context, key *Key, src interface{}) (*Key, error)
Get(c context.Context, key *Key, dst interface{}) error

However, I cannot understand how GET method can possibly work. I tried to replicate behavior with the simplest snippet, but it didn't work.

import "fmt"

type MyType struct {
    inside string
}

func setVal(dst *MyType) {
    someVal := MyType{"new"}
    *dst = someVal
}

func setValGen(dst interface{}) {
    someVal := MyType{"new"}
    dst = someVal
}


func main() {
    typeDstA := MyType{"old"}
    setVal(&typeDstA)
    fmt.Println(typeDstA)     //changed to new

    typeDstB := MyType{"old"}
    setValGen(&typeDstB)
    fmt.Println(typeDstB)     //remains old
}

How they make Get function accept interface{} and change the pointer destination?

Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132
  • Related / possible duplicate: [Changing pointer type and value under interface with reflection](https://stackoverflow.com/questions/46342228/changing-pointer-type-and-value-under-interface-with-reflection/46342394#46342394). – icza Nov 30 '17 at 07:19

1 Answers1

1

Most likely they are using reflection.

https://play.golang.org/p/kU5gKjG0P8

someVal := MyType{"new"}
v := reflect.ValueOf(dst).Elem()
if v.CanSet() {
    v.Set(reflect.ValueOf(someVal))
}
dave
  • 62,300
  • 5
  • 72
  • 93