I want to create N number of structures with proxy data so that later you can walk through them using range . So I could do it like this

 type Proxy struct { Addr []string User []string Password []string } 

And it works great, but it looks somehow not aesthetically pleasing, as I think it would be better to use the []Proxy structure without the Addr, User, Password arrays, the look of the Proxy structure would be like this:

 type Proxy struct { Addr string User string Password string } 

And the code itself would be like this, but the code is wrong:

 package main import ( "fmt" ) type ProxyAuth struct { User, Password string } type Proxy struct { Type int Addr string Auth *ProxyAuth } func New() *[]Proxy { var arr []Proxy return &arr } func (p *[]Proxy) Add(addr, user, pass string) { pnew := Proxy{ Type: 0xff, Addr: addr, Auth: &ProxyAuth{ User: user, Password: pass, }, } p = append(p, pnew) } func main() { p := New() p.Add("192.168.0.1", "test", "test") for i := range p { fmt.Println(p.Addr, p.Auth.User, p.Auth.Password) } } 

Errors:

 invalid receiver type *[]Proxy ([]Proxy is not a defined type)(undefined) p.Add undefined (type *[]Proxy has no field or method Add)(undefined) 

How can this be done more correctly and correctly?

    1 answer 1

    You have several mistakes at once. First, you cannot declare methods on slice types without creating a new type. So that:

     type Proxies []Proxy 

    Secondly, in the Add method, the p parameter is a pointer:

     *p = append(*p, pnew) 

    Thirdly, you misuse the cycle:

     for _, pp := range *p { fmt.Println(pp.Addr, pp.Auth.User, pp.Auth.Password) } 

    Here is the working code: https://play.golang.org/p/JFgkla1tl7A .

    • Thank you very much! Now I understand my mistakes :) - Mothership