This error occurs when you attempt 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 reason behind this is that the first type includes additional tags for JSON serialization, which makes Go treat it as a distinct type from the second one.

To fix this, you can either modify the type of the variable/parameter to match the type of the value you're trying to assign, or adjust the value's type to remove the JSON tags.

For instance, if you wish 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 subsequently copy the values into the desired type variable using a loop or a conversion function.

Alternatively, you can remove the JSON tags from the value's type if they're not required for serialization. This involves defining a new type with the same fields but without the tags, and then converting the original value to the new type. 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})
 }

Here, a new type TimeDuration is defined without any JSON tags, and a loop is used to copy the values from the original slice to a new slice of the desired type.

Go Error: cannot use ([]struct{RecordTime string; Duration float64} literal) as []struct{RecordTime string; Duration float64} - Solution & Explanation

原文地址: https://www.cveoy.top/t/topic/n6UV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录