我在 Go 的列表中有一些值。我只需要能够打印它们,但每次我尝试它都会告诉我 test.FirstName undefined (类型 *list.Element 没有字段或方法 FirstName)。
那么如何正确访问列表中的成员呢?最后几行给我带来了麻烦。
package main
import (
"bufio"
"fmt"
"log"
"strconv"
"strings"
"os"
"container/list"
)
type Student struct {
FirstName string
LastName string
testScore int
homeworkScore int
}
func main() {
fmt.Println("What is the name of your file?\n")
var filename string
fmt.Scan(&filename)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
//var numLineCount int = 0
var gradeCount = 0
var student Student
var studentList list.List
var studentCount int = 1
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
student.FirstName = fields[0]
student.LastName = fields[1]
scanner.Scan()
line2 := scanner.Text()
sum := 0
gradeCount = 0
for _, field := range strings.Fields(line2) {
n, err := strconv.Atoi(field)
if err != nil {
log.Fatal(err)
}
gradeCount++
sum += n
}
student.testScore = sum/gradeCount
gradeCount = 0
scanner.Scan()
line3 := scanner.Text()
sum2 := 0
for _, field := range strings.Fields(line3) {
n, err := strconv.Atoi(field)
if err != nil {
log.Fatal(err)
}
gradeCount++
sum2 += n
}
student.homeworkScore = sum2/gradeCount
studentList.PushBack(studentCount)
studentCount++
fmt.Println("First:", student.FirstName, "Last:", student.LastName, "Test Avg:", student.testScore, "Homework Avg:", student.homeworkScore)
}
test:=studentList.Front()
fmt.Println(test.FirstName)
}
更新:所以我发现我不能在 println 部分使用 test.FirstName ,只有 Println(test) 可以工作并打印所有内容。但我仍然需要能够访问列表中的每个元素。我怎样才能这样做呢?
青春有我
呼如林
相关分类