2013-09-26 38 views
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的內容是什麼,以及在第二種情況下導致副作用的指針解引用是什麼?

回答

2
a := make([]*bufio.Writer, 1) 
a = append(a, tmpwriter) 

然後 LEN(一)== 2和[0] ==零,一[1] == tempwriter, 所以

a[0].WriteString("It's Me") 

恐慌與零參考。


可能是你需要:

var a []*bufio.Writer 
a = append(a, tmpwriter) 
a[0].WriteString("It's Me") 

a := []*bufio.Writer{tmpwriter} 
a[0].WriteString("It's Me") 
+1

或'使([] * bufio.Writer,0,1)' –

+0

唉,我誤解了語義make() - 我認爲它只是保留了空間以避免重新分配,並沒有形成一個這樣大小的分片。第二種形式是la @ 32bitkid,就是我所追求的。 – Bryce