2017-06-16 14 views
0

を初期化しました3構造体:キュー、問題はこの方法で起こっgolangは、空のスライスが後に私が持っている

type Queue struct { 
    Name  string 
    Concurrent int 
    Connections []*redis.Client 
} 

type Config struct { 
    Queues []Queue 
    RedisAddr string 
    RedisDB int 
} 

type Tasker struct { 
    Config Config 
} 

Configを、タスカーは、私は、forループで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? 
} 

外.Connectionsこれは私のテストコード

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() 

} 

理由です5はfor-loopの外側では0ですか?

答えて

2

新しいQueueを作成する代わりに、Config構造で1つにアクセスし、この新しい値がConfig.QueuesQueueに変更を防止しています。 []*QueueConfig.Queues種類を変更し、

// ... 

t.Config.Queues[j].Connections = make([]*redis.Client, queue.Concurrent) 

// ... 

それともauxillary変数を使用したい場合:直接代入してみてください

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}, 
    }, 
} 

今、あなたの元のコードは動作するはずです。