猿问

在不诉诸字符串、strvconv 等的情况下使用 bytes.Buffer

我只想在不求助于 strconv 和字符串的情况下执行此操作,但我不精通仅以字节为单位的工作:


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

}

建议?


喵喵时光机
浏览 159回答 1
1回答

蛊毒传说

没有[]byte与 strconv.Parse* 函数等效的函数(请参阅issue 2632)。使用 strconv 是目前处理此问题的最简单方法。但是,您忽略了第一个错误,这是一个错误。你也可以缩短一些东西,并使用更常见的习语提前返回而不是增加缩进。我也会返回一个错误,而不是返回更多上下文信息的 bool。func rangeSeq(b *bytes.Buffer) ([][]byte, error) {&nbsp; &nbsp; q := bytes.Split(b.Bytes(), sep)&nbsp; &nbsp; if len(q) != 2 {&nbsp; &nbsp; &nbsp; &nbsp; return nil, fmt.Errorf("invalid value: %s", b)&nbsp; &nbsp; }&nbsp; &nbsp; var ret [][]byte&nbsp; &nbsp; initial, err := strconv.Atoi(string(q[0]))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; last, err := strconv.Atoi(string(q[1]))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; if initial < last {&nbsp; &nbsp; &nbsp; &nbsp; for i := initial; i <= last; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ret = append(ret, strconv.AppendInt(nil, i, 10))&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return ret, nil}
随时随地看视频慕课网APP

相关分类

Go
我要回答