Golang如何遍历切片slice

前言

这两天用golang开发一个把企业微信的打卡记录同步到HR-OA系统的一个中间表的功能,同步时把从企业微信接口里查询到的打卡记录放到一个对象的切片里,然后遍历切片把每条打卡记录写到中间表,这里涉及到golang中切片遍历的相关知识,我们在这里一起学习一下Golang如何遍历切片slice

Golang如何遍历切片slice_第1张图片


一、Go遍历切片的两种方式

Go 语言 的 切片 的遍历,有两种方式,分别为:通过 for 循环 与 通过 for range 循环 的方式,类似于 数组 的遍历。

for循环遍历切片

for i := 0; i < len(slice); i++ {
    //slice[i]
}

说明 我们通过 len 函数,获取切片元素的个数,然后通过 for 循环加索引的形式获取每一个切片元素的值。

for range循环遍历切片

for idx, val:= range sliceHaiCoder{
}

说明 通过 for range 的形式来遍历切片元素,idx 即是切片的索引,val 是切片的索引idx 处对应的切片的值。如果我们不需要索引或者值,可以通过 _ 的形式忽略。

for _, val := range sliceHaiCoder{
}

二、企业微信同步打卡信息时遍历切片实际实例

这里只贴出请求业微信接口并把接口返回的数据到到切片中,遍历切片入库的过程,供大家参数,完整代码将在别一篇文章贴出

func Getcheckindata(user UserIdRec, token string, Stime int64, Etime int64, wg *sync.WaitGroup, out chan struct{}) error {
	defer func() {
		wg.Done()
		<-out
	}()
	//获取打卡记录
	var Url string = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=" + token
	var param CheckinDataReq
	param.OpenCheckInDataType = 3
	param.StartTime = Stime
	param.EndTime = Etime
	param.UserIdList = []string{user.Userid}
	paramStr, _ := json.Marshal(param)
	req, err := http.NewRequest("POST", Url, bytes.NewBuffer(paramStr))
	if err != nil {
		log.Println(err.Error())
		return err
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println(err.Error())
		return err
	}
	var Result CheckinDataResult
	err = json.Unmarshal(body, &Result)
	if err != nil {
		return err
	}
	if Result.Errcode == 0 && Result.Errmsg == "ok" {
		var wdmrec WdmCheckinData
		checkTimeStr := ""
		schCheckTimeStr := ""
		locationResult := ""
		timeResult := ""
		for _, rec := range Result.CheckinData {
			log.Println(rec)
			switch rec.CheckinType {
			case "上班打卡":
				wdmrec.CheckType = "OnDuty"
			case "下班打卡":
				wdmrec.CheckType = "OffDuty"
			default:
				wdmrec.CheckType = rec.CheckinType
			}
			//时间异常,地点异常,未打卡,wifi异常,非常用设备如果有多个异常,以分号间隔
			locationResult = "Normal"
			timeResult = "Normal"
			if rec.ExceptionType != "" {
				if strings.Contains(rec.ExceptionType, "地点异常") {
					locationResult = "Outside"
				}
				if strings.Contains(rec.ExceptionType, "时间异常") {
					timeResult = ""
				}
				if strings.Contains(rec.ExceptionType, "未打卡") {
					timeResult = "NotSigned"
				}
				if strings.Contains(rec.ExceptionType, "wifi异常") {
					timeResult = "Outside"
				}
				if strings.Contains(rec.ExceptionType, "非常用设备") {
					locationResult = rec.ExceptionType
				}
			}
			checkTimeStr = time.Unix(rec.CheckinTime, 0).Format("2006/01/02 15:04:05")
			if rec.SchCheckinTime > 0 {
				schCheckTimeStr = time.Unix(rec.SchCheckinTime, 0).Format("2006/01/02") + " 00:00:00"
			}

			wdmrec.DDid = rec.Userid
			wdmrec.LocationResult = locationResult
			wdmrec.RecordId = ""
			wdmrec.UserCheckTime = checkTimeStr
			wdmrec.UserId = rec.Userid
			wdmrec.WorkDate = schCheckTimeStr
			wdmrec.GmtModified = checkTimeStr
			if locationResult == "Normal" && timeResult == "Normal" {
				wdmrec.IsLegal = "Y"
			} else {
				wdmrec.IsLegal = "N"
			}
			wdmrec.BaseCheckTime = time.Unix(rec.CheckinTime, 0).Format("2006/01/02 15:04") + ":00"
			wdmrec.UserAddress = rec.LocationTitle
			wdmrec.TimeResult = timeResult
			wdmrec.DeviceId = rec.DeviceId
			wdmrec.SourceType = "USER"
			wdmrec.PlanCheckTime = checkTimeStr
			wdmrec.GmtCreate = checkTimeStr
			wdmrec.LocationMethod = "MAP"
			wdmrec.PlanId = strconv.Itoa(rec.ScheduleId)
			wdmrec.GroupId = strconv.Itoa(rec.Groupid)
			wdmrec.InsertTime = time.Now().Format("2006-01-02 15:04:05.999")
			DB.Table("LsyncDDforK_Cardwdm").Create(&wdmrec)
			wdmrec.Id = 0
		}
	} else {
		return errors.New(strconv.Itoa(Result.Errcode) + Result.Errmsg)
	}
	return nil

}

总结

Golang语言切片遍历总结,Golang 语言遍历切片只有两种方式通过 for 循环与通过 for range 循环的方式,简单方便。

你可能感兴趣的:(golang,tutorial,golang,开发语言,后端)