【问题标题】:From flag how do you return an (int) instead of an (*int)?从标志如何返回 (int) 而不是 (*int)?
【发布时间】:2014-05-31 12:23:36
【问题描述】:

这个程序返回:

package main

import (
    "flag"
    "fmt"
)

func main() {
    num_agents := flag.Int("a", 10, "number of agents")
    flag.Parse();

    fmt.Printf("%#v",num_agents)
}

输出

(*int)(0x18600110)`

但这不是我想要的……我想要的是整数。

所以根据文档看来我应该使用 flag.IntVar(&pointer_to_variable_integer)

package main

import (
    "flag"
    "fmt"
)

func main() {
    var num_agents int
    flag.IntVar(&num_agents,"a", 10, "number of agents")
    flag.Parse();

    fmt.Printf("%#v",num_agents)
}

但这似乎不对...因为我需要编写 2 行代码,而 1 应该这样做。 在我看来,不知何故

num_agents := flags.Int("a", 10, "number of agents") 

应该返回一个int而不是*int。? 或者也许有一种简单的方法可以从 *int 转换为 int ??

【问题讨论】:

    标签: go


    【解决方案1】:

    简单地取消引用指针:

    num_agents := flags.Int("a", 10, "number of agents")
    fmt.Println(*num_agents)
    

    【讨论】:

    【解决方案2】:

    你也可以试试:

    var num_agents int
    
    func init() {
        flag.IntVar(&num_agents, "a", 10, "number of agents")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 2019-09-15
      • 2015-03-03
      相关资源
      最近更新 更多