kilves76
kilves76

Reputation: 532

Go: Arrays of arrays, arrays of slices, slices of arrays and slices of slices

Trying to teach myself and finding it hard to find examples, and my brain's in a knot already. Very unsure about 3 and 4 and need help for making 5 work.

package main
import "fmt"

func main () {
    println("0. Array:")
    var a = [...]int{4,5,6,7,8,9} //assign
    fmt.Println(a,"\n")

    println("1. Slice:")
    var as []int
    as = a[:] //assign
    fmt.Println(as,"\n")

    println("2. Array of arrays:")
    var b [4][len(a)]int
    for i:= range b { //assign
        b[i]=a
    }
    fmt.Println(b,"\n")

    println("3. Array of slices:")
    var d [len(b)][]int
    for i:= range b { // assign
        d[i] = b[i][:] //does this really work?
    }
    fmt.Println(d,"\n")

    println("4. Slice of arrays:")
    var c [][len(a)]int
    c = b[:][:] // assign, does this really work?
    fmt.Println(c,"\n")

    println("5. Slice of slices:")
    var e [][]int
//  e = c //  ???
    fmt.Println(e,"\n")
}

Upvotes: 5

Views: 3058

Answers (2)

Sonia
Sonia

Reputation: 28355

The answer to "does this really work?" depends on what you are expecting. Consider this example at http://play.golang.org/p/7Z5hKioTI_

package main

import "fmt"

func main() {
    fmt.Println("0. Array:")
    var a = [...]int{4, 5, 6, 7, 8, 9}  //assign
    fmt.Println(a, "\n")

    fmt.Println("1. Slice:")
    var as []int
    as = a[:]   //assign
    fmt.Println(as, "\n")

    fmt.Println("new slice:")
    ns := make([]int, len(a))
    copy(ns, a[:])
    fmt.Print(ns, "\n\n")

    fmt.Println("modifying array...")
    a[0] = 10
    fmt.Print("array is now:\n", a, "\n\n")
    fmt.Print("slice is now:\n", as, "\n\n")
    fmt.Print("new slice is still:\n", ns, "\n")
}

It shows how slices have an underlying array, and that the examples in your OP make slices using the same underlying array. If you want slices to have independent contents, you must make new slices and copy the data. (or there are tricks with append...)

Also as a side note, println sends data to stderr not stdout, and formats some data types differently than fmt.Println. To avoid confusion, it's best to stay in the habit of using fmt.Println.

Upvotes: 1

Stephen Weinberg
Stephen Weinberg

Reputation: 53398

Part 3 works.

Part 4 contains an unnecessary [:].

println("4. Slice of arrays:")
var c [][len(a)]int
c = b[:]    // one [:], not two
fmt.Println(c, "\n")

b[:] is evaluated as a slice where each element is a [len(a)]int. If you add another [:], you are slicing the slice again. Since for any slice s, s[:] == s, it is a no op.

Part 5, you can slice your array of slices.

println("5. Slice of slices:")
var e [][]int
e = d[:]
fmt.Println(e, "\n")

I posted a complete example at http://play.golang.org/p/WDvJXFiAFe.

Upvotes: 6

Related Questions