douao3636 2013-05-04 23:12
浏览 23
已采纳

是否可以通过make()调用结构构造函数?

Is there a better way to allocate the contents of this array, such as automatically calling the NewThing() constructor instead of manually constructing each element?

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

I realize i'm allocating an array of pointers, my other attempts were unsuccessful and data was not an initialized channel. This is just a contrived example.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongqiulei6805 2013-05-05 01:51
    关注

    You can simply write:

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

    Output:

    things:  3
    &{0xc200061020 0xc200062000}
    &{0xc200061040 0xc200062060}
    &{0xc200061060 0xc2000620c0}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳