我正在嘗試從 SQL 服務器上的表中讀取所有行,并將它們存儲在字符串切片中以供以后使用。我遇到的問題是,每次掃描新行時,以前掃描的行都會被覆蓋,即使我已將所有可變字節切片轉換為不可變字符串并將結果切片保存到另一個切片。這是我正在使用的代碼:rawResult := make([]interface{}, len(cols)) // holds anything that could be in a rowresult := make([]string, len(cols)) // will hold all row elements as stringsvar results [][]string // will hold all the result string slicesdest := make([]interface{}, len(cols)) // temporary, to pass into scanfor 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}我確信這與 Go 處理變量和內存的方式有關,但我似乎無法修復它。有人可以解釋我不理解的內容嗎?
- 3 回答
- 0 關注
- 154 瀏覽
添加回答
舉報
0/150
提交
取消