V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
mauve
0.94D

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

  •  
  •   mauve ·
    PRO
    · Jan 17, 2022 · 1591 views
    This topic created in 1571 days ago, the information mentioned may be changed or developed.

    特意去掉了 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  
       Jan 17, 2022
    type Domain struct {
    Apps Apps `json:"apps,omitempty"`
    }
    777777
        2
    777777  
       Jan 17, 2022
    var domain Domain
    app := APP{Id:0, Name:""}
    domain.Apps := []*APP{&app} // 如果要 3 个 []*APP{&app, &app, &app}

    我猜你的需求是因为前端说:空数据也要返回字段。
    eudore
        3
    eudore  
       Jan 18, 2022
    Projects: []*ConfigK8SProject{
    {Project: "dev/*", AutoUpdate: true, Cluster: "local2180", Namespace: "dev"},
    {Project: "test/esb-*", AutoUpdate: true, Cluster: "local2180", Namespace: "test"},
    }
    hzzhzzdogee
        4
    hzzhzzdogee  
       Jan 21, 2022
    前三种都不会出现 { "apps": null}
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   972 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 19:13 · PVG 03:13 · LAX 12:13 · JFK 15:13
    ♥ Do have faith in what you're doing.