donglvmang8638 2019-09-10 21:30
浏览 14

使用docopt输入问题,然后转到

I'm writing some code in go and i want to pass some inputs with docopt. With the first version, I pass via command line only a string, and everything works fine. With the second one, I want to pass two strings and it doesn't work and I get this error:

panic: runtime error: slice bounds out of range [:5] with length 0

goroutine 1 [running]:
main.main()
    /home/user/go/src/github.com/keygen/cmd/keygen/main.go:45 +0xa56

It seems the first string passed has lenght 0.

I think the problem is in the line where I call the Default.Parser, but I can't find the solution. Could you help me?

This is the code not working:

package main

import (
    "fmt"
    "github.com/docopt/docopt.go"
    "github.com/keygen"
    "os"
    "strconv"
)

const usage = `Keygen

Usage:
  keygen (-m|-n|-c) [-l <length>] <serialStart> <serialStop>
  keygen -h | --help

Options:
  -l <length>     Output key length [default: 10].
  -h --help       Show this screen.`

func main() {
    var count keygen.Count
    var Serial string
    var args struct {
        SerialStart  string `docopt:"<serialStart>"`
        SerialStop   string `docopt:"<serialStop>"`
        Length       int    `docopt:"-l"`
        First        bool   `docopt:"-m"`
        Second       bool   `docopt:"-n"`
        Third        bool   `docopt:"-c"`
    }

    opts, err := docopt.DefaultParser.ParseArgs(usage, os.Args[1:], "")
    if err != nil {
        return
    }

        prefix := args.SerialStart[:5]
..........................................

This is the code working:

package main

import (
    "fmt"
    "github.com/docopt/docopt.go"
    "github.com/keygen"
    "os"
)

const usage = `Keygen

Usage:
  keygen (-m|-n|-c) [-l <length>] <serial>
  keygen -h | --help

Options:
  -l <length>     Output key length [default: 10].
  -h --help       Show this screen.`

func main() {
    var count keygen.Count
        var Serial string
    var args struct {
        Serial       string `docopt:"<serial>"`
        Length       int    `docopt:"-l"`
        First        bool   `docopt:"-m"`
        Second       bool   `docopt:"-n"`
        Third        bool   `docopt:"-c"`
    }

    opts, err := docopt.DefaultParser.ParseArgs(usage, os.Args[1:], "")
        if err != nil {
        return
    }

        prefix := args.Serial[:5]
........................................
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?