dongmen9517 2019-07-02 02:03
浏览 656
已采纳

如何在Go中打印列表的值

I've got some values in a list in Go. I just need to be able to print them but every time I try it tells me test.FirstName undefined (type *list.Element has no field or method FirstName).

So how to I appropriately access the members of the list? Its the last couple of lines that are giving me trouble.

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?
") 
    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)

    }

update: so I figured out i can't use test.FirstName in the println part, just Println(test) works and prints everything. but I still need to be able to access each element of the list. How can I do so?

  • 写回答

2条回答 默认 最新

  • douhuang4166 2019-07-02 02:28
    关注

    Seems like you don't have the object type handy. you can use assertion to get the actual object type, something like the following:

      test:=studentList.Front()
      if actualStudent, ok := test.Value.(Student); ok {
          fmt.Println(actualStudent.FirstName)
      }
    

    If it doesn't help, please leave a comment with the issue you face and I will be more than happy to assist you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?