gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:39 26 4
gpt4 key购买 nike

嗨,这里是 Golang 新手,

如何将变量作为指针参数传递给另一个函数。

func B(temp *?, event *Event) {
temp["filla_a"] = event.Data["filla_a"]
return temp
}

func A(event *Event) {
temp := make(map[string]interface{})
temp["po_id"] = event.Data["id"]
temp = B(temp, event)
}

如何在 golang 中实现这一点?

最佳答案

go 中可以这样做:

package main

import (
"fmt"
)

type Event struct {
Data map[string]string
}

func main() {
e := new(Event)
e.Data = make(map[string]string)
e.Data["id"] = "THE_ID"
e.Data["filla_a"] = "THE_FILLA_A"
A(e)
}

func A(event *Event) {
temp := make(map[string]interface{})
temp["po_id"] = event.Data["id"]
B(temp, event)
fmt.Println(temp)
}

func B(temp map[string]interface{}, event *Event) map[string]interface{}{
temp["filla_a"] = event.Data["filla_a"]
return temp
}

我假设/制作了 event 作为 struct 并在程序中声明了相同的内容。

go 中的 map 是一个引用类型(或者更确切地说它具有指向内部数据结构的指针引用),因此您不需要传递一个 map 的指针,只传递/返回变量本身。

另一方面,struct(main() 函数中e 的类型)是value类型并且需要作为指针传递以从被调用函数持久更新。

注意:new 关键字创建指向该类型的指针。因此,main() 函数中的变量 e 实际上是指向 Type Event 的指针。

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

希望对您有所帮助。

关于go - 如何将函数内部创建的变量作为指向另一个函数的指针传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com