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*/
CodePudding user response:
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
CodePudding user response:
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()
}