简体   繁体   中英

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 . 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. 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.

Edit

boxes/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM