从flag中,如何返回一个(int)而不是一个(*int)?

huangapple go评论78阅读模式
英文:

From flag how do you return an (int) instead of an (*int)?

问题

这个程序返回:

package main

import (
    "flag"
    "fmt"
)

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

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

输出:

10

然而这不是我想要的...我想要的是整数。

所以根据文档,我应该使用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)
}

然而这似乎不对...因为我需要写两行代码,而本应只需要一行。
不知何故,我觉得

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

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

英文:

This program returns:

package main

import (
	"flag"
	"fmt"
)

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

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

Outputs

(*int)(0x18600110)`

However that is not what I want... What I want is the integer.

So according to the documentation seems I should use 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)
}

However that doesn't seem right... Because I need to write 2 lines of code when 1 should do.
somehow it seems to me that

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

Should return an int instead of *int.?
Or maybe there is an easy way to cast from *int to int ??

答案1

得分: 2

只需解引用指针:

num_agents := flags.Int("a", 10, "代理数量")
fmt.Println(*num_agents)
英文:

Simply dereference the pointer:

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

答案2

得分: 1

你也可以尝试:

var num_agents int

func init() {
    flag.IntVar(&num_agents, "a", 10, "代理数量")
}
英文:

You can also try:

var num_agents int

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

huangapple
  • 本文由 发表于 2012年6月18日 07:24:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/11075586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定