input directly from cli after a function

54 views
Skip to first unread message

Jabari Zakiya

unread,
Feb 13, 2025, 5:11:45 PM2/13/25
to golang-nuts
I want to input an integer directly after the function

$ ./myfunction n (CR)

not

$ ./myfunction (CR)
    n (CR)

None of my search results  explains how to do this.

Ian Lance Taylor

unread,
Feb 13, 2025, 5:23:10 PM2/13/25
to Jabari Zakiya, golang-nuts
Sounds like you want to look at os.Args, which will contain the
arguments passed to your program on the command line.

Ian

Jabari Zakiya

unread,
Feb 13, 2025, 5:59:29 PM2/13/25
to golang-nuts
Thanks!  This works.

func main() {
  var n int
  s := os.Args[1]
  n, err := strconv.Atoi(s)
  if err != nil {panic(err)}

Jason E. Aten

unread,
Feb 13, 2025, 6:03:56 PM2/13/25
to golang-nuts
If you want to mix flags and "unflagged" arguments, like your integer, see the flag package.

"After parsing, the arguments following the flags are available as the slice flag.Args or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg-1."


Your request is a little confusing because you have called what looks like a program, instead by the name "function". A program always contains the main() function, and typically many other functions as well. A program is executed on the command line in the way that you illustrated: "$ ./your_program "
Reply all
Reply to author
Forward
0 new messages