将命令行参数转换为结构字段

我正在尝试打印一个 JSON(转换为 struct)字段,特别是它作为终端的输入。


type foo struct{ 

field1 string

field2 int

}

这是我创建的结构示例,我想将“field1”作为命令行参数,并通过达到解码的 JSON 输出将其打印到 html 正文或控制台。


通常我可以用这种方式打印它,但我找不到将os.Args[1]值转换为已经定义的结构字段的方法。


var res *foo

_=json.NewDecoder(resp.Body).Decode(&res)

fmt.Println(res.field1)

总之,有没有办法将任何字符串变量转换为函数/方法。非常感谢提前


修订说明:例如。我会写信给终端:


go run main.go "field1"

程序会做这样的事情


fmt.Fprintf(writer, "option.field is %v", someFuncThatConcatenatesThisTwo("option."+ os.Args[1]))

顺便说一句,要调用多个字段。预定义当然可以解决某种情况,但我想学习的是另一回事。


慕斯709654
浏览 120回答 1
1回答

不负相思意

总之,有没有办法将任何字符串转换为函数/方法。我不确定你想在这里实现什么。这没有任何意义。通常,要使用命令行参数填充结构字段,您可以执行以下操作。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "strconv"&nbsp; &nbsp; "os")type Options struct {&nbsp; &nbsp; Field1 string&nbsp; &nbsp; Field2 int64}func main() {&nbsp; &nbsp; if len(os.Args) < 2 {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("missing two required positional arguments: Field1 and Field2")&nbsp; &nbsp; }&nbsp; &nbsp; opts := &Options{}&nbsp; &nbsp; opts.Field1 = os.Args[1]&nbsp; &nbsp; var err error&nbsp; &nbsp; opts.Field2, err = strconv.ParseInt(os.Args[2], 10, 64)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("failed to parse integer value: %v", os.Args[2])&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(opts)}为了让您的生活更轻松,您可以使用flag(或pflag)包将输入参数声明为命令行标志。import (&nbsp; &nbsp; "flag"&nbsp; &nbsp; "fmt")type Options struct {&nbsp; &nbsp; Field1 string&nbsp; &nbsp; Field2 int}var opts Optionsfunc init() {&nbsp; &nbsp; flag.StringVar(&opts.Field1, "field1", "", "help message for field1")&nbsp; &nbsp; flag.IntVar(&opts.Field2, "field2", 0, "help message for field2")&nbsp; &nbsp; flag.Parse()}func main() {&nbsp; &nbsp;fmt.Println(opts)}或者,就像@Jomaar 回答的那样,您可以使用帮助程序库go-arg来避免手动声明命令行标志。另一种选择是go-flags.编辑在进一步澄清之后,您似乎希望使用编写器有选择地编写结构的字段,并且您希望使用位置命令行参数来指定要写入的字段。我认为map在这种情况下存储选项将是一种更合适的数据结构,因为它允许您使用它们的string键简单地引用字段。import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os")func main() {&nbsp; &nbsp; options := map[string]interface{} {&nbsp; &nbsp; &nbsp; &nbsp; "field1": "some-value",&nbsp; &nbsp; &nbsp; &nbsp; "field2": 1,&nbsp; &nbsp; }&nbsp; &nbsp; for _, arg := range os.Args[1:] {&nbsp; &nbsp; &nbsp; &nbsp; if val, ok := options[arg]; ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(val)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}如果要继续使用结构,可以使用reflect包。import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os"&nbsp; &nbsp; "reflect")type Options struct {&nbsp; &nbsp; Field1 string&nbsp; &nbsp; Field2 int}func main() {&nbsp; &nbsp; opts := &Options{Field1: "some-value", Field2: 1}&nbsp; &nbsp; for _, arg := range os.Args[1:] {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(getAttr(opts, arg))&nbsp; &nbsp; }}// copied from https://stackoverflow.com/a/66470232/2410641func getAttr(obj interface{}, fieldName string) (reflect.Value, error) {&nbsp; &nbsp; pointToStruct := reflect.ValueOf(obj) // addressable&nbsp; &nbsp; curStruct := pointToStruct.Elem()&nbsp; &nbsp; if curStruct.Kind() != reflect.Struct {&nbsp; &nbsp; &nbsp; &nbsp; return reflect.Value{}, fmt.Errorf("obj is not a struct")&nbsp; &nbsp; }&nbsp; &nbsp; curField := curStruct.FieldByName(fieldName) // type: reflect.Value&nbsp; &nbsp; if !curField.IsValid() {&nbsp; &nbsp; &nbsp; &nbsp; return reflect.Value{}, fmt.Errorf("field not found: %s", fieldName)&nbsp; &nbsp; }&nbsp; &nbsp; return curField, nil}Go Playground 演示: https:&nbsp;//play.golang.org/p/sch53l2bq4O
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go