好吧,我至少可以告訴你你在做什么。bindQuery需要一個指針。它更改存儲在地址中的值。你基本上做的是這樣的:package mainimport "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 mainimport ( "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 回答

慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
不想NewThing給ThingFactory。
不要創建NewThing函數,除非你有復雜的初始化,或者你故意不導出結構的一部分。選擇性地只設置結構的一部分并不復雜,可以通過使用標簽來完成。復雜的是“槽 Q 的值取決于槽 Zorb 的值”。未導出的結構字段對于信息隱藏很有用,但應謹慎使用。
Go 是垃圾收集的,任何未被引用的數據都有資格被收集。開始時不用擔心它,然后確保清除對不再感興趣的數據的任何引用,以避免意外活躍(“意外活躍”本質上是“內存泄漏”的 GC 等價物”)。
如果您希望經常打印數據結構,請考慮String為它們創建一個方法(這與您所做的打印并不完全對應,但通常可能對向量更有用):
func (v Vector) String() string {
return fmt.Sprintf("V<%d, %d, %d>", v.x v.y, v.z);
}
除非“vect”對您來說真的很重要,否則更喜歡“v”或“vector”作為名稱。
- 1 回答
- 0 關注
- 189 瀏覽
添加回答
舉報
0/150
提交
取消