2 回答

TA貢獻1818條經(jīng)驗 獲得超3個贊
您可以使用反射來設置傳遞的接口。即使將結構引用作為接口傳遞,底層類型信息也不會丟失,我們可以使用反射。
package main
import (
"fmt"
"reflect"
)
type Savable interface {}
type Customer struct {
Name string
}
func GetSaved(id string, s Savable) {
cached := Customer{ Name: id }
c1 := reflect.ValueOf(cached)
reflect.ValueOf(s).Elem().Set(c1)
}
func main() {
c := Customer{}
fmt.Printf("Before: %v\n", c)
GetSaved("bob", &c)
fmt.Printf("After: %v\n", c)
}
這是運行鏈接

TA貢獻1851條經(jīng)驗 獲得超4個贊
這有效,我將它轉換為字節(jié)并將其解組回您的結構。希望這可以幫助。:) 包主要
import (
"encoding/json"
"fmt"
)
type Savable interface{}
type Customer struct {
Name string
} // satisfies 'Savable'
func GetSaved(id string, s Savable) {
// somehow get a reference to the object from cache
cached := Customer{Name: "Bob"}
byt, _ := json.Marshal(cached)
_ = json.Unmarshal(byt, &s)
}
func main() {
c := Customer{}
GetSaved("bob", &c)
fmt.Println(c)
}
運行鏈接: https: //play.golang.org/p/NrBRcRmXRVZ
- 2 回答
- 0 關注
- 203 瀏覽
添加回答
舉報