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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?