2017-07-26 69 views
0
var newR[] struct { 
     id string 
     eventid string 
     excel_id string 
     userid string 
     hallid string 
} 

i := 0 
for rows.Next() { 
    var id, eventid, excel_id, userid, hallid string 
    err = rows.Scan(&id, &eventid, &excel_id, &userid, &hallid) 

    // Here is what I want to do 
    newR[i].id = id 
    newR[i].eventid = eventid 
    newR[i].excel_id = excel_id 
    newR[i].userid = userid 
    newR[i].hallid = hallid 
    i++ 
} 

最後收到錯誤消息「運行時錯誤:索引超出範圍」 在/myapp/app/controllers/app.go(圍繞線122)轉到郎映射多結果

newR[i].id = id 

任何建議或提示將有所幫助。謝謝。

+0

你缺少問題中的關鍵信息,即你​​如何創建切片。我猜你對於你想存儲的數據量來說太小了。 –

回答

0

你並不需要創建一個局部變量爲每個字段,只需創建一個結構,並用它來的數據讀入和使用切片累積結果:

// struct definition must be out of functions body 
type newR struct { 
    id string 
    eventid string 
    excel_id string 
    userid string 
    hallid string 
} 

var newRs []newR 
for rows.Next() { 
    var current newR 
    err = rows.Scan(&current.id, &current.eventid, &current.excel_id, &current.userid, &current.hallid) 
    newRs = append(newRs, r) 
} 

而且還最好是檢查對於rows.Next()rows.Scan(...)之後的錯誤。

0

使用append添加一個新元素並初始化尚未分配的片。

newElement := struct { 
    id string 
    eventid string 
    excel_id string 
    userid string 
    hallid string 
} { 
    id: id, 
    eventid: eventid, 
    excel_id: excel_id, 
    userid: userid, 
    hallid: hallid, 
} 
newR = append(newR, newElement) 

...

對不起,不FMT或對其進行測試,但我打字這個從我的手機。