Go switch语句中的变量范围问题
我有一个程序,它解析一个日志文件并返回一个结构片,其中包含文件中填充的数据 我还编写了一个函数,将结构项添加到上述列表中 但是有一个错误是“不能使用'sf'(type*SegmentationFault)作为type SegmentationFault”,这是由这个函数引起的。我该如何解决这个问题Go switch语句中的变量范围问题,go,Go,我有一个程序,它解析一个日志文件并返回一个结构片,其中包含文件中填充的数据 我还编写了一个函数,将结构项添加到上述列表中 但是有一个错误是“不能使用'sf'(type*SegmentationFault)作为type SegmentationFault”,这是由这个函数引起的。我该如何解决这个问题 func (sfList *SegmentationFaultList) AddItem(item SegmentationFault) []SegmentationFault { sfLis
func (sfList *SegmentationFaultList) AddItem(item SegmentationFault) []SegmentationFault {
sfList.Items = append(sfList.Items, item)
return sfList.Items
}
func parseLogFile(logPath string) (s *SegmentationFaultList){
logFile, err := os.Open(logPath)
checkError(err, "Could not open your log file")
defer logFile.Close()
scanner := bufio.NewScanner(logFile)
parsing := false
sf := new(SegmentationFault)
sfs := []SegmentationFault{}
sfList := SegmentationFaultList{sfs}
var beginRegexp = regexp.MustCompile(`(?i).+\[err\]:F-(\d+): Dump: Segmentation fault at ([\da-z]+)$`)
var endRegexp = regexp.MustCompile(`(?i).+\[info\]:Engine child with pid \d+ terminated`)
var sfTextRegexp = regexp.MustCompile(`(?i).+\[err\]:F-\d+: Dump:(.+)`)
for scanner.Scan() {
beginMatch := beginRegexp.FindStringSubmatch(scanner.Text())
switch {
case beginMatch != nil:
sf.pid = beginMatch[1]
sf.sfAt = beginMatch[2]
parsing = true
case endRegexp.FindStringSubmatch(scanner.Text()) != nil:
parsing = false
sfList.AddItem(sf)
case parsing:
sf.sfText = append(sf.sfText, strings.TrimSpace(sfTextRegexp.FindStringSubmatch(scanner.Text())[1]))
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return sfList
}
您的问题是您正在传递一个指针值(
*SegmentationFault
),而您只需要一个值SegmentationFault
而不是
sf := new(SegmentationFault)
你应该做:
sf := SegmentationFault{}
您有一个指针值(*SegmentationFault
),并且试图将其用作SegmentationFault
。因为new(SegmentationFault)
返回一个*SegmentationFault