I am working on a sample program in golang which is as follows
package main
import (
"fmt"
)
type thing [2]byte
func walk(things []thing, idx int) []byte {
var match []byte
for i, thing := range things {
if i == idx {
match = thing[:]
}
}
return match
}
func main() {
ta := []thing{ thing{'W','A'}, thing{'O','R'} }
m := walk(ta, 0)
tb := []thing{ thing{'C','A'}, thing{'W','Y'}, thing{'N','V'} }
n := walk(tb, 1)
fmt.Printf("m = %s\n", m)
fmt.Printf("n = %s\n", n)
}
The output is:
m = OR
n = NV
I am not sure why this is the case when type thing [2]byte is an array of size 2 and ta is type []thing.
Now when you write the same code as this using [][]byte
package main
import (
"fmt"
)
func walk(things [][]byte, idx int) []byte {
var match []byte
for i, thing := range things {
if i == idx {
match = thing[:]
}
}
return match
}
func main() {
ta := [][]byte{[]byte{'W', 'A'}, []byte{'O', 'R'}}
m := walk(ta, 0)
tb := [][]byte{[]byte{'C', 'A'}, []byte{'W', 'Y'}, []byte{'N', 'V'}}
n := walk(tb, 1)
fmt.Printf("m = %s\n", m)
fmt.Printf("n = %s\n", n)
}
The output is
m = WA
n = WY
I am confused by these different behaviours of slices?
Printing out ta[:]
when ta is type thing []byte
and ta[:] when ta is [][]byte
is the same
thing
is type[2]byte
, not type[]byte
. That is, it's an array, not a slice. The semantics are not the same. – Adrian[2]byte
as elements of the slice, why, in your first example, are returing[]byte
? If you return a[2]byte
(an array) the algorithm works as expected. See for youself what i'm trying to say: play.golang.org/p/wOGaJ9Pwtck. Nevertheless this is a great example for understaning the slice internals.... – Victor