In Go if I have a custom type inherited from let's say a slice of integers if I cast an array of integers to my custom type would it involve new memory allocation?
package main
import (
"fmt"
)
type MyIntsArray []int
func (a MyIntsArray) Sum() int {
sum := 0
for _, i := range a {
sum += i
}
return sum
}
func main() {
myInts := []int{1,2,3,5,7,11}
myIntsArr := MyIntsArray(myInts)
fmt.Println(fmt.Sprintf("myInts: %v, myIntsArr: %v, Sum: %v", myInts, myIntsArr, myIntsArr.Sum()))
}
Update: OK, for slices there is no memory allocation as slices are pointers.
But I have more general question. How about structs? Seems it makes copy: http://play.golang.org/p/NXgM8Cr-qj and it is because of working with value types.
I am trying to figure out if I can cast a pointer to a struct to a pointer of a different type. Something like this: http://play.golang.org/p/BV086ZAeGf
package main
import (
"fmt"
)
type MyType1 struct {
Val int
Values []int
}
type MyType2 MyType1
func main() {
t1 := &MyType1{Val: -1, Values: []int{1,3,5}}
var t2 *MyType2
t2 = *MyType2(t1)
fmt.Printf("t1: %v, t2: %v
", t1, t2)
t1.Val = -10
t1.Values[1] = 200
fmt.Printf("t1: %v, t2: %v
", t1, t2)
}
prog.go:17: cannot convert t1 (type *MyType1) to type MyType2
prog.go:17: invalid indirect of MyType2(t1) (type MyType2)