细节不多多说了,说了也没人看。
问题:通过函数修改切片(不就是数组吗,不知道谁翻译的)的值以及增加元素
代码如下:
type fcltChartDat struct {
DeviceType int `json:"device_type" `
DataType0 []interface{} `json:"data_type0" `
DataType1 []interface{} `json:"data_type1" `
DataType2 []interface{} `json:"data_type2" `
}
...
///!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// 添加元素,注意每个v 的值都要 重新来过!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
v = echartValue{}
v.Value = append(v.Value, xTime)
v.Value = append(v.Value, 0)
chDat.DataType0 = append(chDat.DataType0, v)
v = echartValue{}
v.Value = append(v.Value, xTime)
v.Value = append(v.Value, 0)
chDat.DataType1 = append(chDat.DataType1, v)
v = echartValue{}
v.Value = append(v.Value, xTime)
v.Value = append(v.Value, 0)
chDat.DataType2 = append(chDat.DataType2, v)
// 动态修改 DataType0,DataType1,DataType1 的值或者增加元素
setEndTimeOfPrevEchtValue(&chDat)
setEndTimeOfPrevEchtValue(&chDat)
代码如下:
/// 注意这里的引用方法,即引用指针里的数组元素
func setEndTimeOfPrevEchtValue(chatDat *fcltChartDat) {
SetEndTimeOfDataType(&(chatDat.DataType0))
SetEndTimeOfDataType(&(chatDat.DataType1))
SetEndTimeOfDataType(&(chatDat.DataType2))
}
func SetEndTimeOfDataType(pDatType *[]interface{}) {
//get the last but one value
if len(*pDatType) > 1 {
lastIdx := len(*pDatType) - 2
curIdx := len(*pDatType) - 1
lastDat := (*pDatType)[lastIdx].(echartValue)
curDat := (*pDatType)[curIdx].(echartValue)
lastCnt := lastDat.Value[1].(int)
curCnt := curDat.Value[1].(int)
//如果前面的元素的值和当前值不同,就在当前元素前面插入一个值,当前元素的位置后移一位
if lastCnt != curCnt {
lastV2 := echartValue{}
curVa2 := echartValue{}
// record the current value
curVa2.Value = append(curVa2.Value, curDat.Value[0])
curVa2.Value = append(curVa2.Value, curDat.Value[1])
curTimeStr := curDat.Value[0].(string) // time string
tmpTime, _ := time.Parse("2006-01-02 15:04:05", curTimeStr)
tmpTime = tmpTime.Add(-1 * time.Second)
curTimeStr = tmpTime.Format("2006-01-02 15:04:05")
lastV2.Value = append(lastV2.Value, curTimeStr)
lastV2.Value = append(lastV2.Value, lastCnt)
// change the current arry element value
// 改变当前元素的写法
(*pDatType)[curIdx].(echartValue).Value[0] = lastV2.Value[0]
(*pDatType)[curIdx].(echartValue).Value[1] = lastV2.Value[1]
// make the current value to the tail of the array
*pDatType = append(*pDatType, curVa2)
}
}
指的注意的而是,在使用append 增加数组元素时,数组里面记录的应该是这个元素的地址,因此,如果有一批类似的操作,一定要给每个元素赋予新的实例(相当于 new 一个对象)),否则这些操作添加都是同一个元素,后面处理时,就乱套了。你以为是不同的元素,其实是一个,相互影响,导致逻辑混乱。
maraSun BJFWDQ
核检继续做3天,不知何日昔日还。
探亲聚会非必要,生活只有一盒酸。