4

有没有更好的方法来分配这个数组的内容,比如自动调用NewThing()构造函数而不是手动构造每个元素?

package main

import "sync"

type Thing struct {
    lock *sync.RWMutex
    data chan int
}

func NewThing() *Thing {
    return &Thing{ lock: new(sync.RWMutex), data: make(chan int) }
}

func main() {
    n := 10
    things := make([]*Thing, n)
    for i := 10; i < n; i++ {
        things[i] = NewThing()
    }
}

我意识到我正在分配一个指针数组,我的其他尝试不成功,并且数据不是初始化通道。这只是一个人为的例子。

谢谢!

4

1 回答 1

0

你可以简单地写:

package main

import (
    "fmt"
    "sync"
)

type Thing struct {
    lock *sync.RWMutex
    data chan int
}

func NewThing() *Thing {
    return &Thing{lock: new(sync.RWMutex), data: make(chan int)}
}

func NewThings(n int) []*Thing {
    things := make([]*Thing, n)
    for i := range things {
        things[i] = NewThing()
    }
    return things
}

func main() {
    things := NewThings(3)

    fmt.Println("things: ", len(things))
    for _, thing := range things {
        fmt.Println(thing)
    }
}

输出:

things:  3
&{0xc200061020 0xc200062000}
&{0xc200061040 0xc200062060}
&{0xc200061060 0xc2000620c0}
于 2013-05-05T01:51:11.477 回答