Sorting Golang-扇入式分拣
我随机生成了一组日志消息,在它们生成之后,我需要在将它们写入日志之前按时间戳对它们进行排序。我正在利用Sorting Golang-扇入式分拣,sorting,for-loop,go,concurrency,channel,Sorting,For Loop,Go,Concurrency,Channel,我随机生成了一组日志消息,在它们生成之后,我需要在将它们写入日志之前按时间戳对它们进行排序。我正在利用sort库的sort.Interface特性,以便根据时间戳进行排序。我使用的是扇入式并发设计,所以我的排序函数聚合了来自goroutine的所有日志消息,然后对它们进行排序 这是我的密码: type CommonLogFormat struct { HostIP string UserIdent string User st
sort
库的sort.Interface
特性,以便根据时间戳进行排序。我使用的是扇入式并发设计,所以我的排序函数聚合了来自goroutine的所有日志消息,然后对它们进行排序
这是我的密码:
type CommonLogFormat struct {
HostIP string
UserIdent string
User string
Timestamp string
Request string
HttpStatusCode int
Size int
}
type Logs struct {
Messages []*CommonLogFormat
}
func sortByTimestamp(ch chan <- *CommonLogFormat) *Logs {
logs := &Logs{Messages: make([]*CommonLogFormat, 1)}
for i := range ch {
logs.Messages = append(logs.Messages, <- i)
}
sort.Sort(logs)
return logs
}
func (l Logs) Len() int {
return len(l.Messages)
}
func (l Logs) Less(i,j int) bool {
return l.Messages[i].Timestamp < l.Messages[j].Timestamp
}
func (l *Logs) Swap(i,j int) {
l.Messages[i], l.Messages[j] = l.Messages[j], l.Messages[i]
}
输入CommonLogFormat结构{
HostIP字符串
用户识别字符串
用户字符串
时间戳字符串
请求字符串
HttpStatusCode int
大小整数
}
类型日志结构{
消息[]*CommonLogFormat
}
func sortByTimestamp(ch chan我认为错误消息是不言自明的。请看以下内容:
for i := range ch {
logs.Messages = append(logs.Messages, <- i)
}
对于范围
,循环变量的详细信息如下:
Range expression 1st value 2nd value
array or slice a [n]E, *[n]E, or []E index i int a[i] E
string s string type index i int see below rune
map m map[K]V key k K m[k] V
channel c chan E, <-chan E element e E
范围表达式第一个值第二个值
数组或切片a[n]E、*[n]E或[]E索引i在a[i]E中
字符串的字符串类型索引i int见下面的符文
地图m地图[K]V键K m[K]V
c频道陈E频道,啊,好的。这真的很有道理,谢谢!
for i := range ch {
logs.Messages = append(logs.Messages, i)
}
Range expression 1st value 2nd value
array or slice a [n]E, *[n]E, or []E index i int a[i] E
string s string type index i int see below rune
map m map[K]V key k K m[k] V
channel c chan E, <-chan E element e E