On Sat, Aug 29, 2020 at 2:01 PM Shyaka <renek...@gmail.com> wrote:
>
> Hello, I need help, I have a struct Person wiith list inside, I add 5 string 
> on list at the end I found that the list is nil, I don't know whre is the 
> error, any help is appreciated.
>
> package main
>
> import (
>     "container/list"
>     "fmt"
> )
>
> type Persons struct {
>     name  string
>     Names list.List
> }
>
> func main() {
>
>     p := &Persons{
>         name:  "",
>         Names: *list.New(),
>     }

Your program doesn't work because of the above line. list.New()
creates a new list containing the head/tail pointers within an Element
instance, both pointing to the list created by list.New() by
reference. They do not point to p.Names. When you add elements, those
are added to the list returned by list.New(), not to Person.Names, but
the size of Person.Names is incremented with each addition.

Do not use list.New(), leave the Names uninitialized. It will
initialize correctly the first time you add an element to it.


>     p.setName("John Peter")
>     p.add("one")
>     p.add("two")
>     p.add("three")
>     p.add("four")
>     p.add("five")
>     p.display()
>
> }
>
> func (p *Persons) setName(name string) {
>     p.name = name
> }
> func (p *Persons) add(name string) {
>     p.Names.PushBack(name)
> }
> func (p *Persons) display() {
>     fmt.Println(p.name)
>     for e := p.Names.Front(); e != nil; e = e.Next() {
>         fmt.Println(e.Value)
>     }
> }
>
> --
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/golang-nuts/e8975da6-9af2-4660-8dbb-1a7e7e9b67cfn%40googlegroups.com.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAMV2RqrH6v3wXMN1bw%3D2stUqfMTjB%2B%2BDmaQGYaV6OFw22af%2B_g%40mail.gmail.com.

Reply via email to