英文:
How can I concatenate data from a few files of one package in Golang?
问题
例如,结构如下:
/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}
我理解,这是错误的代码,它会抛出错误,因为我重新声明了变量。我只想问一下,我应该如何将同名变量从同一个包的不同文件中连接起来?
英文:
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?
答案1
得分: 2
你可以使用init()
函数来初始化切片并向其追加元素:
test1.go:
package test
var A = []int{}
func appendA(v ...int) {
A = append(A, v...)
sort.Ints(A) // 根据 @peterSO 的评论,进行排序以确保确定性顺序
}
func init() {
appendA(1, 2)
}
test2.go:
package test
func init() {
appendA(3, 4)
}
英文:
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)
}
答案2
得分: 1
例如,
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)
}
输出:
[1 2 3 3 7]
英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论