douzhulan1815 2019-02-21 02:40
浏览 477

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

This code parse command-line arguments. If I type "/netstat -c /etc/config -I eth0", it should is :" c /etc/config i eth0", but it's not . Terminal output is :

c configfile

c interface

./netstat -c /etc/config -i eth0
c configfile
c interface

Code is as below:

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()

}
  • 写回答

3条回答 默认 最新

  • duanli9930 2019-02-21 04:02
    关注

    It is because you're still holding the default value before flag.Parse() is called:

    // 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()
    

    You can solve the problem by using temporary variables:

    // 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)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?