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})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?