1 回答

TA貢獻1836條經驗 獲得超4個贊
好吧,我至少可以告訴你你在做什么。bindQuery需要一個指針。它更改存儲在地址中的值。
你基本上做的是這樣的:
package main
import "fmt"
func main() {
var q int
myInts := make([]*int, 0, 5)
for i := 0; i < 5; i++ {
q = i
fmt.Printf("%d ", q)
myInts = append(myInts, &q)
}
fmt.Printf("\n")
for _, value := range myInts {
fmt.Printf("%d ", *value)
}
fmt.Printf("\n")
fmt.Println(myInts)
}
正如您可能猜到的那樣,它為您提供了以下信息:
0 1 2 3 4
4 4 4 4 4
[0x104382e0 0x104382e0 0x104382e0 0x104382e0 0x104382e0]
事情變得有點混亂reflect。您可以將您的類型作為接口,但僅此而已(除非您想使用unsafe)。簡單來說,接口包含一個指向底層原始類型(以及其他一些東西)的指針。所以在你的函數中你傳遞了一個指針(和其他一些東西)。然后你要附加指針。只是具體化并鍵入 switch 您的界面可能會很好。我假設你知道它可能是什么類型。在這種情況下,您必須按照以下方式進行操作:
package main
import (
"fmt"
"reflect"
)
type foo struct {
fooval string
}
type bar struct {
barval string
}
func main() {
f1 := foo{"hi"}
f2 := &foo{"hi"}
b1 := bar{"bye"}
b2 := &bar{"bye"}
doSomething(f1)
doSomething(f2)
doSomething(b1)
doSomething(b2)
}
func doSomething(i interface{}) {
n := reflect.TypeOf(i)
// get a new one
newn := reflect.New(n).Interface()
// find out what we got and handle each case
switch t := newn.(type) {
case **foo:
*t = &foo{"hi!"}
fmt.Printf("It was a **foo, here is the address %p and here is the value %v\n", *t, **t)
case **bar:
*t = &bar{"bye :("}
fmt.Printf("It was a **bar, here is the address %p and here is the value %v\n", *t, **t)
case *foo:
t = &foo{"hey!"}
fmt.Printf("It was a *foo, here is the address %p and here is the value %v\n", t, *t)
case *bar:
t = &bar{"ahh!"}
fmt.Printf("It was a *bar, here is the address %p and here is the value %v\n", t, *t)
default:
panic("AHHHH")
}
}
您也可以繼續value = reflect.New(query.structType).Interface()在循環內部調用,每次都會為您提供新的接口。每次追加后重新分配值。上次通過循環會使一個額外的雖然..
- 1 回答
- 0 關注
- 184 瀏覽
添加回答
舉報