英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论