因為對go不是很熟,踫到一個小問題,就是我的系所字串資料已經設定到Depart,但是離開學院的for迴圈後,就都消失了,不知道要怎麼改寫才會成功呢?
底下是經過簡化後,沒有去讀取系所資料庫內容,純粹設定流水字串的程式
package main
import (
"fmt"
"strconv"
)
type Departments struct {
Depart []string // 系所
College string // 學院
}
func main() {
var records []Departments
for i := 0; i < 10; i++ {
recordData := Departments{}
recordData.College = strconv.Itoa(i)
records = append(records, recordData)
}
for _, DepartmentsVaue := range records {
for j := 0; j < 10; j++ {
var recordData string
recordData = strconv.Itoa(j)
DepartmentsVaue.Depart = append(DepartmentsVaue.Depart, recordData)
}
fmt.Println(DepartmentsVaue.Depart)
}
fmt.Println(records)
}
結果如下
————————————————————————————————————————————————————————————————————————
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[{[] 0} {[] 1} {[] 2} {[] 3} {[] 4} {[] 5} {[] 6} {[] 7} {[] 8} {[] 9}]
你可能沒有先搞清楚傳值或傳參考(指標)的運作
你的程式碼
var records []Departments
使得
for _, DepartmentsVaue := range records
是傳值的運作,將records內的每一份資料作拷貝,傳給DepartmentsVaue,所以DepartmentsVaue這時候拿到的是備份後的資料,你去修改備份資料,可以期待原始資料也會改變嗎?這就是問題所在。
改成下面的程式,以傳參考運作
package main
import (
"fmt"
"strconv"
)
type Departments struct {
Depart []string // 系所
College string // 學院
}
func main() {
var records = make([]*Departments, 0)
for i := 0; i < 10; i++ {
recordData := Departments{}
recordData.College = strconv.Itoa(i)
records = append(records, &recordData)
}
for _, DepartmentsVaue := range records {
for j := 0; j < 10; j++ {
var recordData string
recordData = strconv.Itoa(j)
(*DepartmentsVaue).Depart = append((*DepartmentsVaue).Depart, recordData)
}
fmt.Println(DepartmentsVaue.Depart)
}
for _, DepartmentsVaue := range records {
fmt.Println((*DepartmentsVaue))
}
}
結果為
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
{[0 1 2 3 4 5 6 7 8 9] 0}
{[0 1 2 3 4 5 6 7 8 9] 1}
{[0 1 2 3 4 5 6 7 8 9] 2}
{[0 1 2 3 4 5 6 7 8 9] 3}
{[0 1 2 3 4 5 6 7 8 9] 4}
{[0 1 2 3 4 5 6 7 8 9] 5}
{[0 1 2 3 4 5 6 7 8 9] 6}
{[0 1 2 3 4 5 6 7 8 9] 7}
{[0 1 2 3 4 5 6 7 8 9] 8}
{[0 1 2 3 4 5 6 7 8 9] 9}