如何在Go语言中显示学生列表?

huangapple go评论84阅读模式
英文:

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()
}

playground

英文:

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()
}

playground

huangapple
  • 本文由 发表于 2022年9月22日 03:48:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/73806213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定