此代码解析命令行参数。如果我输入“/netstat -c/etc/config -I eth0”,它应该是:“c/etc/config\n i eth0”, 但事实并非如此。终端输出为:
c 配置文件
C接口(interface)
./netstat -c /etc/config -i eth0
c configfile
c interface
代码如下:
package main
import (
"flag"
"fmt"
)
type CmdSt struct {
configPtr string
interfacePtr string
}
var cmdSt CmdSt
func usage() {
cmdSt.configPtr = *flag.String("c", "configfile", "configure file to parse ")
cmdSt.interfacePtr = *flag.String("i", "interface", "capture network interface")
/*
a := flag.String("c", "configfile", "configure file to parse ")
b := flag.String("i", "interface", "capture network interface")
*/
flag.Parse()
fmt.Println("c", cmdSt.configPtr)
fmt.Println("i", cmdSt.interfacePtr)
/*
fmt.Println("c:", *a)
fmt.Println("i:", *b)
*/
}
func main() {
usage()
}
最佳答案
这是因为在调用 flag.Parse()
之前您仍然保留默认值:
// still holding the "configfile" as value
cmdSt.configPtr = *flag.String("c", "configfile", "configure file to parse ")
// still holding the "interface" as value
cmdSt.interfacePtr = *flag.String("i", "interface", "capture network interface")
// flag is parsed now, but both cmdSt.configPtr and cmdSt.interfacePtr still holding the default value because of the pointer.
flag.Parse()
可以通过使用临时变量来解决问题:
// hold the value to temporary variables
a := flag.String("c", "configfile", "configure file to parse ")
b := flag.String("i", "interface", "capture network interface")
// parse the flag and save to the variables.
flag.Parse()
// now, point the value to the CmdSt struct
cmdSt.configPtr = *a
cmdSt.interfacePtr = *b
fmt.Println("c", cmdSt.configPtr)
fmt.Println("i", cmdSt.interfacePtr)
关于go - 为什么我无法在 Go 中将指针字符串转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54798414/