我有3个结构:Queue,Config,Tasker
type Queue struct {
Name string
Concurrent int
Connections []*redis.Client
}
type Config struct {
Queues []Queue
RedisAddr string
RedisDB int
}
type Tasker struct {
Config Config
}
此方法中发生了问题,我在for循环中初始化了queue.Connections,但是我得到了零长度的queue.Connections在for循环之外
func (t *Tasker) StartListening() {
for j := 0; j < len(t.Config.Queues); j++ {
queue := t.Config.Queues[j]
queue.Connections = make([]*redis.Client, queue.Concurrent)
fmt.Println(len(queue.Connections)) //here print correct length, 1 for default queue, 2 for mail queue
}
fmt.Println(len(t.Config.Queues[0].Connections)) //but why here print 0?
}
这是我的测试代码
func main() {
config := Config{
RedisAddr: "10.1.1.59:6379",
RedisDB: 8,
Queues: []Queue{
Queue{Name: "default", Concurrent: 1},
Queue{Name: "mail", Concurrent: 2},
},
}
daemon := Tasker{Config: config}
daemon.StartListening()
}
为什么
fmt.Println(len(t.Config.Queues[0].Connections))
在for循环外为0? 最佳答案
您正在创建一个新的Queue
,而不是访问Config
结构中的一个Queue
,此新值可防止对Config.Queues
中的Config.Queues
进行修改。尝试直接分配:
// ...
t.Config.Queues[j].Connections = make([]*redis.Client, queue.Concurrent)
// ...
或者,如果要使用辅助变量,请将
[]*Queue
类型更改为ojit_code:type Config struct {
Queues []*Queue
RedisAddr string
RedisDB int
}
// ...
config := Config{
RedisAddr: "10.1.1.59:6379",
RedisDB: 8,
Queues: []*Queue{
&Queue{Name: "default", Concurrent: 1},
&Queue{Name: "mail", Concurrent: 2},
},
}
现在,您的原始代码应该可以使用了。
关于for-loop - Golang初始化后得到了空片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44586280/