我試圖從SQL服務器上的表中讀取所有行,並將它們存儲在字符串片中供以後使用。我遇到的問題是,以前掃描的行在每次掃描新行時都會被覆蓋,即使我已將所有可變字節切片轉換爲不可變字符串並將結果切片保存到另一切片。下面是我使用的代碼:SQL掃描的行被覆蓋
rawResult := make([]interface{}, len(cols)) // holds anything that could be in a row
result := make([]string, len(cols)) // will hold all row elements as strings
var results [][]string // will hold all the result string slices
dest := make([]interface{}, len(cols)) // temporary, to pass into scan
for i, _ := range rawResult {
dest[i] = &rawResult[i] // fill dest with pointers to rawResult to pass into scan
}
for rows.Next() { // for each row
err = rows.Scan(dest...) // scan the row
if err != nil {
log.Fatal("Failed to scan row", err)
}
for i, raw := range rawResult { // for each scanned byte slice in a row
switch rawtype := raw.(type){ // determine type, convert to string
case int64:
result[i] = strconv.FormatInt(raw.(int64), 10)
case float64:
result[i] = strconv.FormatFloat(raw.(float64), 'f', -1, 64)
case bool:
result[i] = strconv.FormatBool(raw.(bool))
case []byte:
result[i] = string(raw.([]byte))
case string:
result[i] = raw.(string)
case time.Time:
result[i] = raw.(time.Time).String()
case nil:
result[i] = ""
default: // shouldn't actually be reachable since all types have been covered
log.Fatal("Unexpected type %T", rawtype)
}
}
results = append(results, result) // append the result to our slice of results
}
我敢肯定,這事做與圍棋處理變量和內存的方式,但我似乎無法修復它。有人能解釋我不理解的東西嗎?
謝謝,這是非常不直觀的 –
看看這篇文章。這是非常有用的http://blog.golang.org/slices – RoninDev