英文:
How to display student list in this program in Go language?
问题
package main
import (
"fmt"
)
type Student struct {
rollnumber int
name string
address string
}
func NewStudent(rollno int, name string, address string) *Student {
s := new(Student)
s.rollnumber = rollno
s.name = name
s.address = address
return s
}
type StudentList struct {
list []*Student
}
func (ls *StudentList) CreateStudent(rollno int, name string, address string) *Student {
st := NewStudent(rollno, name, address)
ls.list = append(ls.list, st)
return st
}
func main() {
student := new(StudentList)
student.CreateStudent(24, "Asim", "AAAAAA")
student.CreateStudent(24, "Naveed", "BBBBBB")
fmt.Println(student)
}
当我运行这个程序时,它输出的是地址,而不是我存储的值,请检查并告诉我如何显示实际数据。我是Go的新手。
英文:
package main
import (
"fmt"
)
type Student struct {
rollnumber int
name string
address string
}
func NewStudent(rollno int, name string, address string) *Student {
s := new(Student)
s.rollnumber = rollno
s.name = name
s.address = address
return s
}
type StudentList struct {
list []*Student
}
func (ls *StudentList) CreateStudent(rollno int, name string, address string) *Student {
st := NewStudent(rollno, name, address)
ls.list = append(ls.list, st)
return st
}
func main() {
student := new(StudentList)
student.CreateStudent(24, "Asim", "AAAAAA")
student.CreateStudent(24, "Naveed", "BBBBBB")
fmt.Println(student)
}
/* When I run this program it gives addresses in output instead of the values I stored kindly check and let me know how can I display the actual data. I am a newbie in Go*/
答案1
得分: 2
你可以通过解引用来移除指针:
fmt.Println(*student)
但是你的StudentList.list是一个指向学生的指针数组,所以你也需要解引用它们。我的建议是,除非有充分的理由,不要使用指针。
以下是稍作修改的代码示例:
https://go.dev/play/p/PkNkUF0EFt7
英文:
You can remove the pointer by dereferencing it:
fmt.Println(*student)
But your StudentList.list is an array of pointers to students so you need to derefence those too. My 2 cents, don't use pointers unless you have good reason to.
See your code slightly modified:
https://go.dev/play/p/PkNkUF0EFt7
答案2
得分: 0
你可以在结构体StudentList
上实现Stringer
接口,以修改fmt
包的输出。
以下是示例代码:
...
type StudentList struct {
list []*Student
}
...
func (ls StudentList) String() string {
var b strings.Builder
for _, v := range ls.list {
fmt.Fprintf(&b, "%+v\n", *v)
}
return b.String()
}
英文:
You can implement Stringer
on struct StudentList
to modify the output on fmt
pkg.
This is the example:
...
type StudentList struct {
list []*Student
}
...
func (ls StudentList) String() string {
var b strings.Builder
for _, v := range ls.list {
fmt.Fprintf(&b, "%+v\n", *v)
}
return b.String()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论