我正在學習 golang 并試圖完成 go 之旅。我被困在切片練習上。在此處復制粘貼問題和我的解決方案。有人可以批評它并告訴我我在這里做錯了什么嗎?問題:Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit unsigned integers. When you run the program, it will display your picture,interpreting the integers as grayscale (well, bluescale) values.The choice of image is up to you. Interesting functions include (x+y)/2, x*y, and x^y.(You need to use a loop to allocate each []uint8 inside the [][]uint8.)(Use uint8(intValue) to convert between types.)我的解決方案:package mainimport "golang.org/x/tour/pic"func Pic(dx, dy int) [][]uint8 { ans := make([][]uint8, dy) for i:=0; i< dy; i++ { slice := make([]uint8, dx) for j := 0; j<dx;j++{ slice = append(slice, uint8((i+j)/2)) } ans = append(ans,slice) } return ans}func main() { pic.Show(Pic)}運行時出現(xiàn)錯誤:恐慌:運行時錯誤:索引超出范圍 [0],長度為 0我不確定我在這里做錯了什么。另外,為什么在練習中傳遞了一個函數(shù)?這是故意的嗎?
1 回答

慕神8447489
TA貢獻1780條經驗 獲得超1個贊
好,我知道了。正如我在評論中所說,您應該用slice[j] = uint((i+j)/2)
and替換您的附加調用ans[i] = slice
。
該練習使用 256x256 調用您的函數(shù)。您創(chuàng)建一個 256 長的切片,然后將其他切片附加 256 次,得到一個 512 長的切片ans
。前 256 個條目是空的,因為 appendslice
在末尾追加。因此,當 pic 庫迭代您的數(shù)據(jù)時,它會嘗試訪問一個空切片。
更新:修復算法的另一種方法是初始化長度為 0 的切片。所以編輯
ans := make([][]uint8, 0)
和 slice := make([]uint8, 0)
也應該給出正確的結果。
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報
0/150
提交
取消