douju2474 2018-09-27 16:42
浏览 341
已采纳

[] struct {}和[] * struct {}有什么区别?

What's the difference about below ?

type Demo struct {s string}

func getDemo1()([]*Demo)  // 1

func getDemo2()([]Demo)  // 2

Is there any memory difference between getDemo1 and getDemo2?

  • 写回答

1条回答 默认 最新

  • dpjo15650 2018-09-27 18:58
    关注

    I'm going to answer this, despite my better judgement to just send OP to the tour and documentation/specification. Mostly because of this:

    Is there any memory difference between getDemo1 and getDemo2?

    The answer to this specific question depends on how you utilize the slice. Go is Pass by value, so passing struct values around copies them. For instance, consider the following example.

    https://play.golang.org/p/VzjYXwUy0EI

    d1 := getDemo1()
    d2 := getDemo2()
    for _, v := range d1 {
        // v is of type *Demo, so this modifies the value in the slice
        v.s = "same"
    }
    fmt.Println(d1)
    
    for _, v := range d2 {
        // v is of type Demo, and is a COPY of the struct in the slice, so the original is not modified
        v.s = "same"
    }
    

    So as to the memory question, obviously using *Demo, which returns a copy of the pointer in the range (effectively a uint64) as opposed to returning a copy of a Demo (the entire struct and all it's fields) would use less memory. BUT, you can still index directly to the array to avoid copies, except when you pass individual items in the slice around.

    That said, passing the slice itself around, the two types have no difference in overhead. A slice is an abstraction of an array, and the slice itself that gets passed around is merely a slice header, which would be the same memory footprint regardless what type the slice contains.

    BTW, the paradigm for modifying the values in the case of []Demo is:

    for i, _ := range d2 {
        d2[i].s = "same"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题