Go 如何通过指针访问结构数组?
下面是我的2个结构Go 如何通过指针访问结构数组?,go,struct,Go,Struct,下面是我的2个结构 type Attempt struct { StartTime string `json:"startTime"` EndTime string `json:"endTime"` LastUpdated string `json:"lastUpdated"` Duration uint32 `json:"duration"` SparkUser string `js
type Attempt struct {
StartTime string `json:"startTime"`
EndTime string `json:"endTime"`
LastUpdated string `json:"lastUpdated"`
Duration uint32 `json:"duration"`
SparkUser string `json:"sparkUser"`
IsCompleted bool `json:"completed"`
LastUpdatedEpoch int64 `json:"lastUpdatedEpoch"`
StartTimeEpoch int64 `json:"startTimeEpoch"`
EndTimeEpoch int64 `json:"EndTimeEpoch"`
}
type Apps struct {
Id string `json:"id"`
Name string `json:"name"`
Attempts []Attempt `json:"attempts"`
}
下面的测试将json字符串解析为这个apps:=&[]apps{}
。访问应用程序
的成员时,我遇到以下错误
invalid operation: apps[0] (type *[]Apps does not support indexing)
测试
func TestUnmarshalApps(t *testing.T) {
appsJson := `[
{
"id": "app-20161229224238-0001",
"name": "Spark shell",
"attempts": [
{
"startTime": "2016-12-30T03:42:26.828GMT",
"endTime": "2016-12-30T03:50:05.696GMT",
"lastUpdated": "2016-12-30T03:50:05.719GMT",
"duration": 458868,
"sparkUser": "esha",
"completed": true,
"endTimeEpoch": 1483069805696,
"lastUpdatedEpoch": 1483069805719,
"startTimeEpoch": 1483069346828
},
{
"startTime": "2016-12-30T03:42:26.828GMT",
"endTime": "2016-12-30T03:50:05.696GMT",
"lastUpdated": "2016-12-30T03:50:05.719GMT",
"duration": 458868,
"sparkUser": "esha",
"completed": true,
"endTimeEpoch": 1483069805696,
"lastUpdatedEpoch": 1483069805719,
"startTimeEpoch": 1483069346828
}
]
},
{
"id": "app-20161229222707-0000",
"name": "Spark shell",
"attempts": [
{
"startTime": "2016-12-30T03:26:50.679GMT",
"endTime": "2016-12-30T03:38:35.882GMT",
"lastUpdated": "2016-12-30T03:38:36.013GMT",
"duration": 705203,
"sparkUser": "esha",
"completed": true,
"endTimeEpoch": 1483069115882,
"lastUpdatedEpoch": 1483069116013,
"startTimeEpoch": 1483068410679
}
]
}
]`
apps := &[]Apps{}
err := json.Unmarshal([]byte(appsJson), apps)
if err != nil {
t.Fatal(err)
}
if len(*apps) != 2 {
t.Fail()
}
if len(apps[0].Attempts) != 2 {
t.Fail()
}
}
如何访问字段尝试、Id等
apps := &[]Apps{}
apps
具有类型*[]apps
(指向apps对象切片的指针)
您确定不是要使用类型[]*Apps
(指向Apps对象的指针片段)吗
假设*[]应用程序
确实是您想要的类型,您需要使用(*Apps)[i]
访问应用程序
的每个元素。这种类型也是您还需要使用len(*apps)
而不是len(apps)
(实际上几乎所有东西都需要*apps
)的原因
apps
具有类型*[]apps
(指向apps对象切片的指针)
您确定不是要使用类型[]*Apps
(指向Apps对象的指针片段)吗
假设
*[]应用程序
确实是您想要的类型,您需要使用(*Apps)[i]
访问应用程序
的每个元素。这种类型也是为什么你也需要使用len(*apps)
而不是len(apps)
(实际上几乎所有东西都要使用*apps
)我可以这样做吗:apps:=[]apps{};err:=json.Unmarshal([]字节(appsJson),&apps)@AravindR.Yarram当然,只要你的apps
类型没有任何需要指针接收器的方法(即你没有func(a*apps)方法(…)
),你就可以这样做。否则,您可能需要使用[]*Apps{}
;err:=json.Unmarshal([]字节(appsJson),&apps)@AravindR.Yarram当然,只要你的apps
类型没有任何需要指针接收器的方法(即你没有func(a*apps)方法(…)
),你就可以这样做。否则,您可能需要使用[]*应用程序{}
。