dou7851 2019-04-19 08:08
浏览 122

Golang:创建切片结构

I want to create a list of structs that can be returned by a function in a manner as it is in the go-github package.

But what is the correct way to create and populate such a list?

I found two ways, e.g., using the append():

...
    allowedRepos := strings.Fields("repo1, repo2")

    actualRepos := []Repos{}
    actualRepos = append(actualRepos, Repos{Name: "repo1", URL: "gth.com/repo1"})
    actualRepos = append(actualRepos, Repos{Name: "repo2", URL: "gth.com/repo2"})
...

And by a "direct initialization:

...
    actualRepos := []Repos{
        Repos{Name: "repo1", URL: "gth.com/repo1"},
        Repos{Name: "repo2", URL: "gth.com/repo2"},
    }  

They works but both look bit awkward and wrong.

So - what is the best way to do it?

It looks like need to create it using pointer but can't make it work.

  • 写回答

1条回答 默认 最新

  • douxing2652 2019-04-19 08:55
    关注

    but both look bit awkward and wrong

    Actually there is nothing wrong, both approaches are correct and valid.
    The only difference - is slice population time.
    In 2nd approach you're populating slice during development time, it means this code:

    actualRepos := []Repos{
        Repos{Name: "repo1", URL: "gth.com/repo1"},
        Repos{Name: "repo2", URL: "gth.com/repo2"},
    } 
    

    always will create slice with 2 elements in it.

    But wit 1st approach you can populate slice in runtime using append(), like:

    actualRepos := []Repos{}
    for _, repo := range allRepos {
      actualRepos = append(actualRepos, repo)
    }
    

    so now all depends on allRepos and now this code have dynamic behaviour which is determined in runtime.

    It looks like need to create it using pointer

    Please pay attention that slice itself passes by reference, for example:

    s := [...]string{"r", "o", "a", "d"}
    s2 := s[:]
    s[3] = "x"
    

    Result will be:

    // s = [r o a x], s2 = [r o a x]
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度