Range over custom type

4,839 views
Skip to first unread message

Craig Wickesser

unread,
Dec 23, 2014, 12:22:18 PM12/23/14
to golan...@googlegroups.com
I am trying to range over a custom type which is a slice of custom things, an example will help:

type Widget struct {
 
Name string
 
Price int
}

type
Widgets []Widget

func
(w *Widgets) Find(name string) Widget {
 
for widget := range w {
     
if widget.Name == name {
       
return widget
     
}
 
}
 
return nil
}



I get an error when trying to build:

cannot range over w (type *Widgets)

thoughts? answers?

cm...@golang.org

unread,
Dec 23, 2014, 12:27:51 PM12/23/14
to golan...@googlegroups.com
You can't range over a pointer to a slice, dereference it first e.g. you probably want something like `range *w`.

Shawn Milochik

unread,
Dec 23, 2014, 12:30:37 PM12/23/14
to golan...@googlegroups.com

This modifications works for me.

Adam Vincze

unread,
Dec 23, 2014, 12:32:06 PM12/23/14
to golan...@googlegroups.com
you are ranging over a pointer to a slice of pointers

try to dereference 
other than that, you cannot return nil for a value object  it should be *Widget

like so

Craig Wickesser

unread,
Dec 23, 2014, 12:39:49 PM12/23/14
to golan...@googlegroups.com, Sh...@milochik.com
Thanks, dereferencing was the issue.
Reply all
Reply to author
Forward
0 new messages