英文:
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("v", 0, "verbosity")
flag.Parse() // <- this
// and dereferencing the *int pointer
if *verbose != 0 {
log.Print("I'm verbose")
}
}
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'm verbose
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论