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.

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

报告相同问题?

悬赏问题

  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题