如何在Golang中将一个包中几个文件的数据连接起来?

huangapple go评论90阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2014年9月3日 22:51:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/25647473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定