[英]Is their a way to use pointers to append items to golang array from inside a struct or function
I am working on an open source personal project called Box .我正在开发一个名为Box 的开源个人项目。 I am currently working on making it easier to add more boxes, both for my self and for others.我目前正在努力让添加更多盒子变得更容易,无论是为我自己还是为他人。 I have a function in boxes/boxes.go that returns an array with all the different box names.我在 box/boxes.go 中有一个函数,它返回一个包含所有不同框名称的数组。 I was wondering if I could use pointers or some other tool to be able to add elements to the array without having to know that the elements exist.我想知道是否可以使用指针或其他一些工具来将元素添加到数组中,而不必知道这些元素是否存在。 eg you write a third-party box and it will add itself to the list of boxes either when you install it or when box is run.例如,您编写了一个第三方框,它会在您安装或运行时将自身添加到框列表中。 I am thinking of using an initialization function, but I am not sure how to implement it.我正在考虑使用初始化函数,但我不确定如何实现它。 Any help would be highly appreciated.任何帮助将不胜感激。
boxes/boxes.go盒子/boxes.go
package boxes
var Boxes []string
func GetBoxes() *[]string {
return &Boxes
}
Boxes are just strings in this case.在这种情况下,框只是字符串。
Lets say I have可以说我有
// SomeFile.go
package new_box
import boxes_package
func AddBox() {
allBoxes := GetBoxes() // returns a pointer
// do some stuff and add "some box" to Boxes from boxes/boxes.go
}
I have tried我试过了
func AddBox() {
boxes := GetBoxes()
*boxes = append(*boxes, "some box")
}
and it works but I need to call it somewhere它有效,但我需要在某个地方调用它
Answer回答
package boxes
var Boxes []string
func GetBoxes() *[]string {
return &Boxes
}
func AddBox(name string) bool {
Boxes = append(Boxes, name)
return true
}
and then I just called AddBox in SomeFile.go然后我在 SomeFile.go 中调用了 AddBox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.