Skip to content

Learning Go – Miniblog #3 – Starting to code

January 9, 2013

This carries on from here.

Having decided what I’m going to build, I need to decide which bit to build first. Obviously, I’m going to need an HTTP server, but I reckon I’ll put that off. Equally obviously, I’m going to need to read files and list directories. This is pretty simple stuff in most languages, so that’s where I’ll start.

I’d also better read some tutorial materials on Go. The sensible place to start would seem to be the site called A Tour of Go, so I have a flick through that. Nothing really surprising – Go seems to be very much like C. Some of the nuances escape me for the moment, but hopefully they will become clear as I actually write some code. Onwards!

I’m going to need to specify things like file and directory names on the command line, so the first small program I decide to write is something that simply lists the command line arguments, so if I enter a command like

go run cmdline.go foo bar zod

it should print out something like:

Number of args is 4
arg 0 is cmdline.go
arg 1 is foo
arg 2 is bar
arg 3 is zod

From the Tour page, it seems like the main() function in Go does not provide you with the command line – presumably it’s available in some global variable. Time to look at the Go Packages documentation!

This turns out not to be so easy, but I eventually work out that the os package is the one I want. Searching through that it seems that the Argv slice is what I want. Here’s the complete documentation for it:

var Args []string

Args hold the command-line arguments, starting with the program name.

The rest of the documentation seems equally minimalistic (which I don’t mind too much) and provides almost no examples of the use the documented features (which I mind a lot – there can be no excuses for this).

Anyway, with that information, I get to write this stunning code:

package main
import "fmt"
import "os"
func main() {
    fmt.Printf( "Number of args is %d\n", len( os.Args ) )
    for idx,val := range( os.Args ) {
        fmt.Printf( "arg %d is %s\n", idx, val )
    }
}

which does the job. Will the documentation (or lack of it) cause problems for my next challenge – listing the contents of files with line numbers? Wait and see…

Advertisements

From → golang

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: