donglianglu8136 2017-01-22 22:45
浏览 47
已采纳

如何通过引用传递,以便可以在调用函数中对其进行修改?

How can I pass something to a function such that it is modifiable and can be seen in the calling stack ? ( in other words how to pass a pointer or a reference ? )

package main

import (
    "os/exec"
    "fmt"
)

func process(names *[]string) {
    fmt.Print("Pre process", names)
    names[1] = "modified"
}

func main() {    
    names := []string{"leto", "paul", "teg"}
    process(&names)

    fmt.Print("Post process", names)
}

Error:
invalid operation: names[0] (type *[]string does not support indexing)
  • 写回答

1条回答 默认 最新

  • dongshan4878 2017-01-22 22:53
    关注

    Dereferencing a pointer has higher precedence.
    Here is a code that works: https://play.golang.org/p/9Bcw_9Uvwl

    package main
    
    import (
        "fmt"
    )
    
    func process(names *[]string) {
        fmt.Println("Pre process", *names)
        (*names)[1] = "modified"
    }
    
    func main() {
        names := []string{"leto", "paul", "teg"}
        process(&names)
        fmt.Println("Post process", names)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码