V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
mauve
V2EX  ›  Go 编程语言

[]*Struct 类型的变量应该使用哪种方式初始化?

  •  
  •   mauve · 2022-01-17 11:26:35 +08:00 · 1076 次点击
    这是一个创建于 801 天前的主题,其中的信息可能已经有所发展或是发生改变。

    特意去掉了 omitempty tag

    为了防止出现

    {
        "apps": null
    }
    
    

    最推荐的声明方式应该是哪一种?

    package main
    
    type App struct {
    	Id   int    `json:"id"`
    	Name string `json:"name"`
    }
    
    type Apps []*App
    
    type Domain struct {
    	Apps Apps
    }
    
    const CustomCapacity = 3
    
    func main() {
    	apps1 := make([]*App, 0, CustomCapacity)
    	apps2 := make([]App, 0, CustomCapacity)
    	apps3 := make(Apps, 0, CustomCapacity)
    	apps4 := Apps{}
    	apps5 := &Apps{}
    }
    
    
    MidGap
        1
    MidGap  
       2022-01-17 14:20:10 +08:00
    type Domain struct {
    Apps Apps `json:"apps,omitempty"`
    }
    777777
        2
    777777  
       2022-01-17 17:13:44 +08:00
    var domain Domain
    app := APP{Id:0, Name:""}
    domain.Apps := []*APP{&app} // 如果要 3 个 []*APP{&app, &app, &app}

    我猜你的需求是因为前端说:空数据也要返回字段。
    eudore
        3
    eudore  
       2022-01-18 09:07:50 +08:00
    Projects: []*ConfigK8SProject{
    {Project: "dev/*", AutoUpdate: true, Cluster: "local2180", Namespace: "dev"},
    {Project: "test/esb-*", AutoUpdate: true, Cluster: "local2180", Namespace: "test"},
    }
    hzzhzzdogee
        4
    hzzhzzdogee  
       2022-01-21 22:48:48 +08:00
    前三种都不会出现 { "apps": null}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1129 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:56 · PVG 06:56 · LAX 15:56 · JFK 18:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.