A Tutorial for the Go Programming Language

Author: google. Link to original: http://golang.org/doc/go_tutorial.html (English).

Translations of this material:

into Russian: Язык программирования Go. 18% translated in draft.
Submitted for translation by kron0s 04.12.2009 Published 2 years, 5 months ago.

Text

Introduction

Hello, World

Compiling

Echo

An Interlude about Types

An Interlude about Allocation

An Interlude about Constants

An I/O Package

Rotting cats

Sorting

Printing

Prime numbers

Multiplexing

Introduction[Top]

This document is a tutorial introduction to the basics of the Go programming language, intended for programmers familiar with C or C++. It is not a comprehensive guide to the language; at the moment the document closest to that is the language specification. After you've read this tutorial, you might want to look at Effective Go, which digs deeper into how the language is used. Also, slides from a 3-day course about Go are available: Day 1, Day 2, Day 3.

The presentation here proceeds through a series of modest programs to illustrate key features of the language. All the programs work (at time of writing) and are checked into the repository in the directory /doc/progs/.

Program snippets are annotated with the line number in the original file; for cleanliness, blank lines remain blank.

Hello, World[Top]

Let's start in the usual way:

05 package main

07 import fmt "fmt" // Package implementing formatted I/O.

09 func main() { 10 fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n"); 11 }

Every Go source file declares, using a package statement, which package it's part of. It may also import other packages to use their facilities. This program imports the package fmt to gain access to our old, now capitalized and package-qualified, friend, fmt.Printf.

Functions are introduced with the func keyword. The main package's main function is where the program starts running (after any initialization).

String constants can contain Unicode characters, encoded in UTF-8. (In fact, Go source files are defined to be encoded in UTF-8.)

The comment convention is the same as in C++:

/* ... */

// ...

Later we'll have much more to say about printing.

Compiling[Top]

Go is a compiled language. At the moment there are two compilers. Gccgo is a Go compiler that uses the GCC back end. There is also a suite of compilers with different (and odd) names for each architecture: 6g for the 64-bit x86, 8g for the 32-bit x86, and more. These compilers run significantly faster but generate less efficient code than gccgo. At the time of writing (late 2009), they also have a more robust run-time system although gccgo is catching up.

Here's how to compile and run our program. With 6g, say,

$ 6g helloworld.go # compile; object goes into helloworld.6

$ 6l helloworld.6 # link; output goes into 6.out

$ 6.out

Hello, world; or Καλημέρα κόσμε; or こんにちは 世界

$

With gccgo it looks a little more traditional.

$ gccgo helloworld.go

$ a.out

Hello, world; or Καλημέρα κόσμε; or こんにちは 世界

$

Echo[Top]

Next up, here's a version of the Unix utility echo(1):

05 package main

07 import ( 08 "os"; 09 "flag"; // command line option parser 10 )

12 var omitNewline = flag.Bool("n", false, "don't print final newline")

14 const ( 15 Space = " "; 16 Newline = "\n"; 17 )

19 func main() { 20 flag.Parse(); // Scans the arg list and sets up flags 21 var s string = ""; 22 for i := 0; i < flag.NArg(); i++ { 23 if i > 0 { 24 s += Space 25 } 26 s += flag.Arg(i); 27 } 28 if !*omitNewline { 29 s += Newline 30 } 31 os.Stdout.WriteString(s); 32 }

This program is small but it's doing a number of new things. In the last example, we saw func introduce a function. The keywords var, const, and type (not used yet) also introduce declarations, as does import. Notice that we can group declarations of the same sort into parenthesized, semicolon-separated lists if we want, as on lines 7-10 and 14-17. But it's not necessary to do so; we could have said

const Space = " "

const Newline = "\n"

Semicolons aren't needed here; in fact, semicolons are unnecessary after any top-level declaration, although they are needed as separators within a parenthesized list of declarations.

You can use semicolons just the way you would in C, C++, or Java, but if you prefer you can also leave them out in many cases. They separate statements rather than terminate them, so they aren't needed (but are still OK) at the end of the last statement in a block. They're also optional after braces, as in C. Have a look at the source to echo. The only necessary semicolons in that program are on lines 8, 15, and 21 and of course between the elements of the for loop on line 22. The ones on line 9, 16, 26, and 31 are optional but are there because a semicolon on the end of a list of statements makes it easier to edit the list later.

This program imports the "os" package to access its Stdout variable, of type *os.File. The import statement is actually a declaration: in its general form, as used in our ``hello world'' program, it names the identifier (fmt) that will be used to access members of the package imported from the file ("fmt"), found in the current directory or in a standard location. In this program, though, we've dropped the explicit name from the imports; by default, packages are imported using the name defined by the imported package, which by convention is of course the file name itself. Our ``hello world'' program could have said just import "fmt".

You can specify your own import names if you want but it's only necessary if you need to resolve a naming conflict.

Given os.Stdout we can use its WriteString method to print the string.

Having imported the flag package, line 12 creates a global variable to hold the value of echo's -n flag. The variable omitNewline has type *bool, pointer to bool.

In main.main, we parse the arguments (line 20) and then create a local string variable we will use to build the output.

The declaration statement has the form

var s string = "";

This is the var keyword, followed by the name of the variable, followed by its type, followed by an equals sign and an initial value for the variable.

Go tries to be terse, and this declaration could be shortened. Since the string constant is of type string, we don't have to tell the compiler that. We could write

var s = "";

or we could go even shorter and write the idiom

s := "";

The := operator is used a lot in Go to represent an initializing declaration. There's one in the for clause on the next line:

22 for i := 0; i < flag.NArg(); i++ {

The flag package has parsed the arguments and left the non-flag arguments in a list that can be iterated over in the obvious way.

The Go for statement differs from that of C in a number of ways. First, it's the only looping construct; there is no while or do. Second, there are no parentheses on the clause, but the braces on the body are mandatory. The same applies to the if and switch statements. Later examples will show some other ways for can be written.

The body of the loop builds up the string s by appending (using +=) the flags and separating spaces. After the loop, if the -n flag is not set, the program appends a newline. Finally, it writes the result.

Notice that main.main is a niladic function with no return type. It's defined that way. Falling off the end of main.main means ''success''; if you want to signal an erroneous return, call

os.Exit(1)

The os package contains other essentials for getting started; for instance, os.Args is a slice used by the flag package to access the command-line arguments.

An Interlude about Types[Top]

Go has some familiar types such as int and float, which represent values of the ''appropriate'' size for the machine. It also defines explicitly-sized types such as int8, float64, and so on, plus unsigned integer types such as uint, uint32, etc. These are distinct types; even if int and int32 are both 32 bits in size, they are not the same type. There is also a byte synonym for uint8, which is the element type for strings.

Speaking of string, that's a built-in type as well. Strings are immutable values—they are not just arrays of byte values. Once you've built a string value, you can't change it, although of course you can change a string variable simply by reassigning it. This snippet from strings.go is legal code:

11 s := "hello";

12 if s[1] != 'e' { os.Exit(1) }

13 s = "good bye";

14 var p *string = &s;

15 *p = "ciao";

However the following statements are illegal because they would modify a string value:

s[0] = 'x';

(*p)[1] = 'y';

In C++ terms, Go strings are a bit like const strings, while pointers to strings are analogous to const string references.

Yes, there are pointers. However, Go simplifies their use a little; read on.

Arrays are declared like this:

var arrayOfInt [10]int;

Arrays, like strings, are values, but they are mutable. This differs from C, in which arrayOfInt would be usable as a pointer to int. In Go, since arrays are values, it's meaningful (and useful) to talk about pointers to arrays.

The size of the array is part of its type; however, one can declare a slice variable, to which one can assign a pointer to any array with the same element type or—much more commonly—a slice expression of the form a[low : high], representing the subarray indexed by low through high-1. Slices look a lot like arrays but have no explicit size ([] vs. [10]) and they reference a segment of an underlying, often anonymous, regular array. Multiple slices can share data if they represent pieces of the same array; multiple arrays can never share data.

Slices are much more common in Go programs than regular arrays; they're more flexible, have reference semantics, and are efficient. What they lack is the precise control of storage layout of a regular array; if you want to have a hundred elements of an array stored within your structure, you should use a regular array.

When passing an array to a function, you almost always want to declare the formal parameter to be a slice. When you call the function, take the address of the array and Go will create (efficiently) a slice reference and pass that.

Using slices one can write this function (from sum.go):

09 func sum(a []int) int { // returns an int

Pages: ← previous Ctrl next
1 2 3 4 5 6

© google.