2 回答

TA貢獻1898條經驗 獲得超8個贊
SplitFunc
提供給的默認值bufio.NewScanner
包括SplitLines
一個調用dropCR
,根據注釋,該調用在行尾匹配\r?\n
。因為Scanner
會選擇性地查找和刪除回車符,所以您將無法使用bufio.Scanner
.
根據我的經驗,在基本情況下使用 Scanner 是很常見的,因為它是一個方便的結構。否則 bufio.Reader 提供了更大的靈活性。bufio.Reader#ReadBytes(delim byte)
會給你你正在尋找的東西。

TA貢獻1845條經驗 獲得超8個贊
雖然這是一個答案,從字面意義上回答了我關于包括\n和潛在的\r問題,但在閱讀 IMAP 服務器的響應時首先使用 Scanner 并不是正確的工具,我將重寫我對 Scanner 的使用并替換它與 bufio.Reader。
您可以指定在掃描器中使用的自定義拆分函數,例如,您可以將 ScanLines 拆分函數移植到一個不會使用返回的令牌丟棄換行符的函數。
// ...
r := bufio.NewScanner(d.conn)
r.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, '\n'); i >= 0 {
// We have a full newline-terminated line.
return i + 1, data[0 : i+1], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
})
for r.Scan() {
line := r.Text()
len(line) // now gets the line length WITH the newline
}
- 2 回答
- 0 關注
- 169 瀏覽
添加回答
舉報