For example, structure:
/src
main.go
/test
test1.go
test2.go
, main.go
package main
import (
"fmt"
"./test"
)
func main(){
fmt.Println(test.A)
}
test1.go:
package test
var A = []int{1,2,3}
test2.go:
package test
var A = []int{3,7}
I understand, that it's a wrong code, it throws the error, because I'm redeclaring the variable. I just want to ask, which way should I go to concatenate this same-name variables from files of one package?
You could initiate the slice and the append to it using the init()
functions :
test1.go:
package test
var A = []int{}
func appendA(v ...int) {
A = append(A, v...)
sort.Ints(A) // sort to make deterministic order per @peterSO comment
}
func init() {
appendA(1, 2)
}
test2.go:
package test
func init() {
appendA(3, 4)
}
For example,
test1.go
:
package test
var A []int
func init() {
A = append(a1, a2...)
}
var a1 = []int{1, 2, 3}
test2.go
:
package test
var a2 = []int{3, 7}
main.go
:
package main
import (
"fmt"
"test"
)
func main() {
fmt.Println(test.A)
}
Output:
[1 2 3 3 7]