doupo2241 2019-08-04 19:49
浏览 65
已采纳

如何为包含Google自动生成的lib的切片的结构初始化

I'm trying to make a Google Analytics Go library based off the auto generated package generated here

I have authenticated, got account summaries etc. so all is well until I try to construct a reporting request.

I am trying to init a struct ReportRequest that has the following:

type ReportRequest struct {

    DateRanges []*DateRange `json:"dateRanges,omitempty"`

    ...etc
}

How can I made a function that wraps this struct so I can pass in the values? Consulting the DateRange struct it seems simple enough, but I get messages about not passing in a slice pointer to DateRange which I can't figure out how to construct.

I have tried this:

func makeRequest(
    start, end string) *ga.GetReportsRequest {

    daterangep := &ga.DateRange{StartDate: start, EndDate: end}

    requests := ga.ReportRequest{}
    requests.DateRanges = daterangep

But get a compiler error:

cannot use daterangep (type *analyticsreporting.DateRange) as type []*analyticsreporting.DateRange in assignment

Is it possible to send in JSON? I see some MarshalJSON functions that I don't know if I can use,and the json declaration in the object but I'd prefer to be able to use Go objects.

Can anyone point to what I'm doing wrong?

  • 写回答

1条回答 默认 最新

  • dongquepao8653 2019-08-04 20:20
    关注

    To initialize a slice you can use a literal:

    daterangep := []*ga.DateRange{{StartDate: start, EndDate: end}}
    

    You can use make:

    daterangep := make([]*ga.DateRange, 1)
    daterangep[0] = &ga.DateRange{StartDate: start, EndDate: end}
    

    Or you can declare it and then use append:

    var daterangep []*ga.DateRange
    daterangep = append(daterangep, &ga.DateRange{StartDate: start, EndDate: end})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况