cannot use structRecordTime string; Duration float64 literal value of type structRecordTime string jsontimestamp; Duration float64 jsonaverage as structRecordTime string; Duration float64 value in ass
This error occurs when you try to assign a value of type []struct{RecordTime string "json:"timestamp""; Duration float64 "json:"average""} to a variable or parameter of type []struct{RecordTime string; Duration float64}.
The issue is that the former type has additional tags for JSON serialization, and Go considers it to be a distinct type from the latter.
To fix this error, you can either change the type of the variable or parameter to match the type of the value you're trying to assign, or modify the type of the value to remove the JSON tags.
For example, if you want to assign a JSON-encoded value to a variable of type []struct{RecordTime string; Duration float64}, you can first decode the JSON into a variable of type []struct{RecordTime string "json:"timestamp""; Duration float64 "json:"average""}, and then copy the values into a variable of the desired type using a loop or a conversion function.
Alternatively, you can modify the type of the value to remove the JSON tags, if you don't need them for serialization. This can be done by defining a new type with the same fields but without the tags, and then converting the original value to the new type. For example:
type TimeDuration struct {
RecordTime string
Duration float64
}
var values = []struct{RecordTime string "json:\"timestamp\""; Duration float64 "json:\"average\""}{
{"2021-06-01T00:00:00Z", 1.23},
{"2021-06-01T01:00:00Z", 4.56},
}
var times []TimeDuration
for _, v := range values {
times = append(times, TimeDuration{v.RecordTime, v.Duration})
}
In this example, we define a new type TimeDuration without any JSON tags, and then use a loop to copy the values from the original slice to a new slice of the desired type
原文地址: https://www.cveoy.top/t/topic/feCj 著作权归作者所有。请勿转载和采集!