duannian3494 2015-08-26 14:41
浏览 50
已采纳

工作一个bytes.Buffer而无需使用字符串,strvconv等

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条回答 默认 最新

  • douluo3256 2015-08-26 14:48
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?