我想引用 CSV 文档中的所有字段。有没有办法修改golang的csv模块而不必复制所有代码?在另一种语言中,我只需继承 csv.Writer 并 override fieldNeedsQuotes
,但这在 Go 中是不可能的,或者是吗?
Matt 和 Volker 已经说过,您可以复制该模块并对其进行修改。
您也可以使用 Writer 包装器,但我认为它有点复杂。将我的尝试视为概念证明(不使用*)。
type quoteWriter struct {
w io.Writer
}
func (w quoteWriter) Write(p []byte) (n int, err error) {
q := make([]byte, 0)
quoted := true
quoted = (p[0] == '"')
if !quoted {
//begin field quote
q = append(q, '"')
}
for i, v := range p {
//We check the "quotation" status for new field or line
//This is a simplification
if v == ',' || v == '\n' {
if !quoted { //end field quote
q = append(q, '"')
}
//copy current byte
q = append(q, v)
//is next byte quote?
if len(p) > i+1 {
quoted = (p[i+1] == '"')
}
if !quoted { //begin field quote
q = append(q, '"')
}
} else {
q = append(q, v)
}
}
return w.w.Write(q)
}
Run Code Online (Sandbox Code Playgroud)
请参阅下面来自 csv#Writer 测试 ( http://golang.org/src/pkg/encoding/csv/writer_test.go )的示例,并应用了概念验证:
http://play.golang.org/p/wovYUkt6Vq
不使用*请注意,我没有检查所有情况,例如,逗号是否在引用的文本中,因此您需要检查并调整它。我还建议复制并修改 csv 包。