如何检查整数标志是否被设置。

huangapple go评论75阅读模式
英文:

How to check if int flag is set

问题

如何检查指针int标志是否已设置?

package main

import (
	"flag"
	"log"
)

var verbose *int

func main() {
	verbose = flag.Int("v", 0, "verbosity")

	if *verbose != 0 {
		log.Print("I'm verbose")
	}
}

错误信息:

无法将0(无类型的int常量)转换为*int
英文:

How to check if pointer int flag is set?

package main

import (
	"flag"
	"log"
)

var verbose *int

func main(){
	verbose = flag.Int("v", 0, "verbosity")
	
	if verbose != 0 {
		log.Print("I'm verbose")
	}
}

error

cannot convert 0 (untyped int constant) to *int

答案1

得分: 0

你缺少了一些东西:

func main() {
    verbose = flag.Int("v", 0, "verbosity")

    flag.Parse() // <- 这里

    // 还有解引用 *int 指针
    if *verbose != 0 {
        log.Print("I'm verbose")
    }
}

flag.Parse 文档中可以看到:

... 从 os.Args[1:] 解析命令行标志。必须在所有标志被定义之后和程序访问标志之前调用。

输出结果:

$ ./ff -v 2

2022/10/11 18:53:18 I'm verbose
英文:

You're missing a couple of things:

func main() {
	verbose = flag.Int(&quot;v&quot;, 0, &quot;verbosity&quot;)

	flag.Parse() // &lt;- this

    // and dereferencing the *int pointer
	if *verbose != 0 {
		log.Print(&quot;I&#39;m verbose&quot;)
	}
}

From the flag.Parse docs:

> ... parses the command-line flags from os.Args[1:]. Must be called
> after all flags are defined and before flags are accessed by the
> program.

Output:

$ ./ff -v 2

2022/10/11 18:53:18 I&#39;m verbose

huangapple
  • 本文由 发表于 2022年10月12日 06:37:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/74034752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定