dqbn76906 2017-10-27 21:31
浏览 39
已采纳

打印切片的内容

Apologies if this is wrong to begin with. I am attempting to learn Golang, and am working through various concepts. I am pretty sure I am confusing something here... I am trying to write a simple program that creates a struct called 'person' which accepts firstname, lastname, and age. I want a user to be able to specify the number of people they will be entering into a slice of struct person, then iterate through the number of people entered, taking the input and storing it in the slice of person. Then, I want to be able to print one of those 'person' to terminal, for instance the 6th one (assuming that many were entered). Here is what I have so far:

package main

import "fmt"

func main() {
    var people int

    type person struct {
        firstName string
        lastName  string
        age       int
    }

    listOfPeople := make([]person, 10)

    fmt.Println("Please enter the number of users you would like to   create:")
    fmt.Scan(&people)

    for i := 0; i < people; i++ {
        var a, b string
        var c int
        fmt.Println("Please enter a person's information: ")
        fmt.Print("First Name: ")
        fmt.Scan(&a)
        fmt.Print("Last Name: ")
        fmt.Scan(&b)
        fmt.Print("Age: ")
        fmt.Scan(&c)
        listOfPeople = append(listOfPeople, person{a, b, c})
    }
    //Print the contents of listOfPeople
}

Where the code comment "print the contents of listOfPeople is where I would like to be able to print a 'person'. I have tried a couple of things but nothing prints or compilation fails. Without attempting to print out a person from listOfPeople the code compiles and runs. I know I am missing something here. Any help is appreciated. I realize this code is likely not optimized or there may be a simpler way of doing it, so if there is please feel free to correct me. Thank you

  • 写回答

1条回答 默认 最新

  • dongmoxin7111 2017-10-27 22:21
    关注

    You're appending to a slice of already allocated 10 people, so you may think that the first person you appended is on the 0th index but it's actually be on the 10th.

    https://play.golang.org/p/bPXsdWk9sa

    What you probably want is something like this

    https://play.golang.org/p/kcfzJ4M0Wp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!