dongtong2021 2015-01-13 06:40 采纳率: 0%
浏览 157
已采纳

Golang取消引用函数返回值

I'm messing with the flag library, and found that this code does not work:

package main

import (
    "fmt"
    "flag"
)

var recursive bool

func init() {
    recursive = *flag.Bool("r", false, "Search recursively")
}
func main() {
    flag.Parse()

    fmt.Printf("Recursive: %t 

", recursive)

    flag.PrintDefaults()

}

But this does (I commented the three lines I changed):

package main

import (
    "fmt"
    "flag"
)

var recursive *bool   //Changed to pointer type

func init() {
    recursive = flag.Bool("r", false, "Search recursively") //Changed to not dereference function
}
func main() {
    flag.Parse()

    fmt.Printf("Recursive: %t 

", *recursive)  //Changed to dereference variable

    flag.PrintDefaults()

}

Why does this behave like this? Are functions not allowed to be dereferenced in Golang, or am I doing something else wrong?

  • 写回答

1条回答 默认 最新

  • doutan6286 2015-01-13 07:08
    关注

    The reason for this is because when you call flag.Bool(), it does not yet parse the command line arguments, it just defines a named flag and initializes it with the default value (which is false as you specified it).

    Command line arguments are only parsed when you call flag.Parse(). If you use recursive bool, in the init() function the default false will be assigned to it. The flag package does not know about your recursive variable, so later when you call flag.Parse(), its value will not/ cannot be changed.

    flag.Bool() returns a pointer to a bool variable which the flag package knows about, and later when you call flag.Parse() the pointed bool variable will be properly updated, so when you print the pointed valued after flag.Bool(), it will be the updated value which will be set based on your command line arguments.

    Alternative: Register your variable

    So you must store and use the pointer returned by flag.Bool() else you will only see the default value. Or you can let the flag package know about your recursive variable: you can tell the flag package that you what it to store the result into your recursive variable by telling this with the flag.BoolVar() function:

    flag.BoolVar(&recursive, "r", false, "Search recursively")
    

    Note that in this case there is no return value, becase you explicitly provided a pointer to a bool which you want the flag package to store the result to.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问各位,如何在Jetson nano主控板的Ubuntu系统中安装PyQt5
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥150 求 《小魔指》街机游戏机整合模拟软件