dtebrq0245 2018-08-17 13:04
浏览 63
已采纳

为什么我不能使用flag.StringVar传递指向fmt.Println的指针?

I've started looking at Golang, and following an example to pass in command line arguments, I've got this code:

package main

import (
    "flag"
    "fmt"
)

func main() {

    wordPtr := flag.String("namestring", "stringvalue", "Pass in a string")
    numPtr := flag.Int("number", 11, "Pass in an int")
    boolPtr := flag.Bool("switchflag", false, "Pass in a bool")
    var svar string
    flag.StringVar(&svar, "svar", "svarstringvalue", "A string variable")
    flag.Parse()

    fmt.Println("Word:", *wordPtr)
    fmt.Println("Word2:", wordPtr)
    fmt.Println("numb:", *numPtr)
    fmt.Println("numb2", numPtr)
    fmt.Println("switchflag", *boolPtr)
    fmt.Println("switchflag2", boolPtr)
    fmt.Println("svar:", svar)
    fmt.Println("svar2", &svar)
    fmt.Println("svar3", *svar) //<-- This won't work...
    fmt.Println("tail:", flag.Args())

}

My question is, why do I get the value of the other pointers if I dereference it (like *wordPtr etc), whereas if I pass wordPtr in, I get the memory address, but with svar, I have to pass in svar to get the value, and &svar gets me the memory address?

Looking at the documentation here https://golang.org/pkg/flag/, it says that you pass in a variable to store the flag (presumably a variable that is already created?), but I still don't understand why I have to do something different to it to get the value, when compared with other variables.

This is the result of me running it with passing in some commands:

➜  Documents go run main.go -number 42 -switchflag -svar testtringvalue
Word: stringvalue
Word2: 0xc42005c1e0
numb: 42
numb2 0xc4200160a0
switchflag true
switchflag2 0xc4200160a8
svar: testtringvalue
svar2 0xc42005c1f0
tail: []

Any help is appreciated. Also, if I've got any understanding of it wrong, please let me know.

Cheers.

  • 写回答

1条回答 默认 最新

  • dongyanfeng0546 2018-08-17 13:12
    关注

    Well this is fairly simple, you are trying to dereference a value instead of pointer.

    var svar string is not a pointer, but a value.

    fmt.Println("svar3", svar) is correct use in this case

    Don't worry about about use of StringVar as ...Var(&svar, "sv... means that you are passing address of svar not a value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改