1
該代碼產生一個無解引用:切片VS指向作家
tmpfile, _ := ioutil.TempFile("", "testing")
defer tmpfile.Close()
tmpwriter := bufio.NewWriter(tmpfile)
defer tmpwriter.Flush()
tmpwriter.WriteString("Hello World\n")
a := make([]*bufio.Writer, 1)
a = append(a, tmpwriter)
a[0].WriteString("It's Me") //Error here
該代碼產生不無解引用,但實際上並沒有寫入任何臨時文件:
tmpfile, _ := ioutil.TempFile("", "testing")
defer tmpfile.Close()
tmpwriter := bufio.NewWriter(tmpfile)
defer tmpwriter.Flush()
tmpwriter.WriteString("Hello World\n")
a := make([]bufio.Writer, 1)
a = append(a, *tmpwriter) //Dereferencing seems to cause the first string not to get written
a[0].WriteString("It's Me")
我在這裏錯過了什麼原則?什麼是存儲一部分作家的慣用方式,以及在第一種情況下導致nil的內容是什麼,以及在第二種情況下導致副作用的指針解引用是什麼?
或'使([] * bufio.Writer,0,1)' –
唉,我誤解了語義make() - 我認爲它只是保留了空間以避免重新分配,並沒有形成一個這樣大小的分片。第二種形式是la @ 32bitkid,就是我所追求的。 – Bryce