Append to a slice inside a range loop

4,283 views
Skip to first unread message

Frank Blechschmidt

unread,
Mar 13, 2013, 1:31:22 PM3/13/13
to golan...@googlegroups.com
Hey!

Is it possible to append to a slice/array inside a loop and keep the changes after leaving the loop?

Example:

result[][]string //filled array with entries from a database
result2[][]string //filled array with additional information for database entries
for i, entry := range result {
entry = append(entry, result2[i][1])
fmt.Println("i: ", i)
fmt.Println("entry: ", entry)
}
fmt.Println("Final result", result)

When I print the entry inside them loop, it looks like how I want it.
When I print the final result, all appended data is lost.

Beste regards
Frank

steve wang

unread,
Mar 13, 2013, 1:38:12 PM3/13/13
to golan...@googlegroups.com
The only thing you need to do is to put back the resized slice.

for i, entry := range result {
entry = append(entry, result2[i][1])
        result[i] = entry     // <=======
fmt.Println("i: ", i)
fmt.Println("entry: ", entry)
}


Frank Blechschmidt

unread,
Mar 13, 2013, 1:45:02 PM3/13/13
to golan...@googlegroups.com
Thanks, man :)

matt

unread,
Mar 15, 2013, 5:34:31 AM3/15/13
to golan...@googlegroups.com
Wouldn't this be more idiomatic as

for i, _ := range result {
result[i] = append(result[i], result2[i][1])
fmt.Printf("[%d] entry: %s\n", i, result[i])

David DENG

unread,
Mar 15, 2013, 5:52:44 AM3/15/13
to golan...@googlegroups.com
This is anyway better:

for i := range result {
result[i] = append(result[i], result2[i][1])
fmt.Printf("[%d] entry: %s\n", i, result[i])
}

David

Dave Cheney

unread,
Mar 15, 2013, 10:07:56 AM3/15/13
to David DENG, golan...@googlegroups.com
In Go 1.1, the former is rewritten by the compiler to be identical to
your example.
> --
> 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...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Nate Finch

unread,
Mar 15, 2013, 12:05:50 PM3/15/13
to golan...@googlegroups.com, David DENG
Awesome. :)

On Friday, March 15, 2013 10:07:56 AM UTC-4, Dave Cheney wrote:
In Go 1.1, the former is rewritten by the compiler to be identical to
your example.

On Fri, Mar 15, 2013 at 8:52 PM, David DENG <david...@gmail.com> wrote:
> This is anyway better:
>
> for i := range result {
>
Reply all
Reply to author
Forward
0 new messages