gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:30:59 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com