英文:
working a bytes.Buffer without resorting to strings, strvconv, etc
问题
我只会翻译你提供的文本内容,以下是翻译结果:
我只是想在不使用strconv和strings的情况下完成这个操作,但我不擅长只使用字节进行操作:
func rangeSeq(b *bytes.Buffer) ([][]byte, bool) {
q := bytes.Split(b.Bytes(), []byte{SEQ_RANGE})
if len(q) == 2 {
var ret [][]byte
il, lt := string(q[0]), string(q[1])
initial, err := strconv.ParseInt(il, 10, 64)
last, err := strconv.ParseInt(lt, 10, 64)
if err == nil {
if initial < last {
for i := initial; i <= last; i++ {
out := strconv.AppendInt([]byte{}, i, 10)
ret = append(ret, out)
}
}
return ret, true
}
}
return nil, false
}
有什么建议吗?
英文:
I would simply like to do this without resorting to strconv & strings, but I am not proficient working in bytes only:
func rangeSeq(b *bytes.Buffer) ([][]byte, bool) {
q := bytes.Split(b.Bytes(), []byte{SEQ_RANGE})
if len(q) == 2 {
var ret [][]byte
il, lt := string(q[0]), string(q[1])
initial, err := strconv.ParseInt(il, 10, 64)
last, err := strconv.ParseInt(lt, 10, 64)
if err == nil {
if initial < last {
for i := initial; i <= last; i++ {
out := strconv.AppendInt([]byte{}, i, 10)
ret = append(ret, out)
}
}
return ret, true
}
}
return nil, false
}
suggestions?
答案1
得分: 3
strconv.Parse*
函数没有 []byte
的等效版本(参见 issue 2632)。目前,使用 strconv 是处理这个问题最简单的方法。
但是,你忽略了第一个错误,这是一个 bug。你还可以简化一些东西,并使用更常见的习惯用法,即提前返回而不是增加缩进。我还建议返回一个错误,而不是一个布尔值,以提供更多的上下文信息。
func rangeSeq(b *bytes.Buffer) ([][]byte, error) {
q := bytes.Split(b.Bytes(), sep)
if len(q) != 2 {
return nil, fmt.Errorf("invalid value: %s", b)
}
var ret [][]byte
initial, err := strconv.Atoi(string(q[0]))
if err != nil {
return nil, err
}
last, err := strconv.Atoi(string(q[1]))
if err != nil {
return nil, err
}
if initial < last {
for i := initial; i <= last; i++ {
ret = append(ret, strconv.AppendInt(nil, i, 10))
}
}
return ret, nil
}
英文:
There is no []byte
equivalent to the strconv.Parse* functions (see issue 2632). Using strconv is currently the easiest way to handle this.
You are ignoring the first error however, which is a bug. You can also shorten a couple things, and use the more common idiom of returning early instead of increasing indentation. I would also return an error, instead of a bool for more contextual information.
func rangeSeq(b *bytes.Buffer) ([][]byte, error) {
q := bytes.Split(b.Bytes(), sep)
if len(q) != 2 {
return nil, fmt.Errorf("invalid value: %s", b)
}
var ret [][]byte
initial, err := strconv.Atoi(string(q[0]))
if err != nil {
return nil, err
}
last, err := strconv.Atoi(string(q[1]))
if err != nil {
return nil, err
}
if initial < last {
for i := initial; i <= last; i++ {
ret = append(ret, strconv.AppendInt(nil, i, 10))
}
}
return ret, nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论