dongtuo5262 2018-11-03 01:45
浏览 110
已采纳

如何将在函数内部创建的变量作为另一个函数的指针传递

Hi Golang newbie here,

How to pass a variable as pointer argument to the another function.

  1. func B(temp *?, event *Event) {
  2. temp["filla_a"] = event.Data["filla_a"]
  3. return temp
  4. }
  5. func A(event *Event) {
  6. temp := make(map[string]interface{})
  7. temp["po_id"] = event.Data["id"]
  8. temp = B(temp, event)
  9. }

How to achive this in golang ?

  • 写回答

1条回答 默认 最新

  • douxiajia6104 2018-11-03 02:21
    关注

    This is how you can do it in go:

    1. package main
    2. import (
    3. "fmt"
    4. )
    5. type Event struct {
    6. Data map[string]string
    7. }
    8. func main() {
    9. e := new(Event)
    10. e.Data = make(map[string]string)
    11. e.Data["id"] = "THE_ID"
    12. e.Data["filla_a"] = "THE_FILLA_A"
    13. A(e)
    14. }
    15. func A(event *Event) {
    16. temp := make(map[string]interface{})
    17. temp["po_id"] = event.Data["id"]
    18. B(temp, event)
    19. fmt.Println(temp)
    20. }
    21. func B(temp map[string]interface{}, event *Event) map[string]interface{}{
    22. temp["filla_a"] = event.Data["filla_a"]
    23. return temp
    24. }

    I have assumed/made event as struct and declared the same in the program.

    The map in go is a reference type (or better say it has pointer reference to internal data structures), so you do not need to pass a pointer of map, just pass/return the variable itself.

    On the other hand struct (the Type of e in the main() function) is value type and need to be passed as a pointer to persist updates from called function.

    NOTE: the new keyword creates a pointer to the type. Thus the variable e in the main() function is actually a pointer to the Type Event.

    Go Playground: https://play.golang.org/p/Jbkm6z5a2Az

    Hope it helps.

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部