doulun0651 2016-04-15 09:16
浏览 243
已采纳

GoLang:在Go中进行类型继承和转换的内存分配

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?

http://play.golang.org/p/cNpKELZ3X- :

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)
  • 写回答

3条回答 默认 最新

  • duanri1985 2016-04-15 20:55
    关注

    Your code would compile with just

    t2 = (*MyType2)(t1)
    

    http://play.golang.org/p/lUGo-mxAOa

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog