go - 为什么我无法在 Go 中将指针字符串转换为字符串?

标签 go

此代码解析命令行参数。如果我输入“/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/

相关文章:

go - wsl 2 中的 PATH 变量总是 reset 。如何解决?

使用 Dockerfile/go.mod 文件的私有(private)存储库的 Go 构建失败

struct - Golang 结构数组值不 append 在循环中

go - 什么标志 fmt.Printf 递归地跟随指针?

go - 编写传递匿名函数作为参数的高阶函数

go - 如何在 Go 中生成可变长度的随机数

http - 返回错误之前如何收集尽可能多的信息

go - 在启用隐私的链代码之间传递查询

go - 使用 GoQuery 在换行符上拆分元素

c++ - 转到 http : no such file after sending image from Qt client