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 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决