dongzhao5834 2019-04-17 13:55
浏览 51
已采纳

go-修改切片的指针不会修改原始的

I try to create a struct where one field is a pointer to the existing empty slice. Then I modify struct's field, and later I try to get the new content from the original slice - but it's still empty!

Here is the demo code:

package main

import (
    "fmt"
)

type A struct {
    B []int
}

func main() {
    c := []int{}

    a := &A{
        B: c,
    }

    a.B = append(a.B, 5)

    fmt.Println(c)
    fmt.Println(a)
}

The result here is:

[]
&{[5]}

The question is - how do I get the actual slice content from both original slice and struct's field? I have no passing the slice to the function as a param here.

  • 写回答

1条回答 默认 最新

  • dsbx40787736 2019-04-17 15:07
    关注

    You can use a slice of pointers like in example below:

    package main
    
    import (
        "fmt"
    )
    
    type A struct {
        B *[]int
    }
    
    func main() {
        c := []int{}
    
        a := &A{
            B: &c,
        }
    
        *a.B = append(*a.B, 4)
        *a.B = append(*a.B, 5)
    
        fmt.Println(c)
    
        fmt.Println(a.B)
    }
    

    Result The result is

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度