我是一名享受Go的Python程序员。让我兴奋的事情通常是使用参考文献;我(大多数时候)已经掌握了它,但有时候会让我感到困惑,比如这个。
我有一个简单的类型('Fixture'):
type Fixture struct {
Probabilities *[]float64
}
如果我为此类型的单个实例填充概率字段,一切都很好:
c := appengine.NewContext(r)
f := Fixture{}
p := []float64{}
p = append(p, 0.5)
p = append(p, 0.2)
p = append(p, 0.3)
f.Probabilities = &p
c.Infof("%v", *f.Probabilities)
2013/03/19 07:37:36 INFO: [0.5 0.2 0.3]
但是,如果我尝试为这些类型的数组填充此字段,则代码将编译,但字段值始终为nil:
c := appengine.NewContext(r)
fixtures := []Fixture{}
f := Fixture{}
fixtures = append(fixtures, f)
for _, f := range fixtures {
p := []float64{}
p = append(p, 0.5)
p = append(p, 0.2)
p = append(p, 0.3)
f.Probabilities = &p
}
for _, f := range fixtures {
// c.Infof("%v", *f.Probabilities) // causes error
c.Infof("%v", f.Probabilities)
}
2013/03/19 07:37:41 INFO: <nil>
我想我不理解数组/切片是如何工作的,特别是在引用方面。谁能指出我哪里出错?
谢谢!
答案 0 :(得分:5)
在范围声明
中for _, f := range fixtures { ... }
f
是一个新声明的Fixture
类型的局部变量。这不是任何事情的参考。因此,在设置其值后,必须将其放入fixtures
切片。
package main
import "fmt"
type Fixture struct {
Probabilities *[]float64
}
func main() {
fixtures := []Fixture{}
f := Fixture{}
fixtures = append(fixtures, f)
for i, f := range fixtures {
p := []float64{}
p = append(p, 0.5)
p = append(p, 0.2)
p = append(p, 0.3)
f.Probabilities = &p
fixtures[i] = f
}
for _, f := range fixtures {
fmt.Printf("%v", f.Probabilities)
}
}
(还here)
输出
&[0.5 0.2 0.3]
答案 1 :(得分:0)
将元素值存储在切片中。例如,
package main
import "fmt"
type Fixture struct {
Probabilities *[]float64
}
func main() {
fixtures := make([]Fixture, 1)
for i := range fixtures {
p := []float64{0.5, 0.2, 0.3}
fixtures[i] = Fixture{Probabilities: &p}
}
for _, f := range fixtures {
fmt.Println(*f.Probabilities)
}
}
输出:
[0.5 0.2 0.3]