The Go Programming Language Part 1

Rob Pike
r@google.com

(updated June 2011)

Wednesday, June 15, 2011

Who
Work done by a small team at Google, plus lots of contributors from around the world. Contact:
http://golang.org: golang-nuts@golang.org: golang-dev@golang.org:

web site user discussion developers

Wednesday, June 15, 2011

Course Outline
Day 1 Basics Day 2 Types, methods, and interfaces Day 3 Concurrency and communication This course is about programming in Go, not about programming language design. That is the topic of a separate talk, not yet on line.

Wednesday, June 15, 2011

June 15.Today’s Outline Motivation Basics the easy. mostly familiar stuff Packages and program construction Wednesday. 2011 .

2011 .Motivation Wednesday. June 15.

concurrency poorly supported. Multi-core seen as crisis not opportunity. Types get in the way too much. 2011 . languages don't help enough: Computers fast but software construction slow. Garbage collection.Why a new language? In the current world. safety. June 15. Wednesday. Dependency analysis necessary for speed.

compile to machine language so it runs fast .the feel of a dynamic language with the safety of a static type system . 2011 . concurrency .real run-time that supports GC. June 15.has methods but not a conventional OO language Wednesday. .lightweight.To put it in a positive way Our goal is to make programming fun again. flexible type system .

2011 . see the documentation: http://golang.Resources For more background.org/ Includes: language specification tutorial "Effective Go" library documentation setup and how-to docs FAQs a playground (run Go from the browser) more Wednesday. June 15. etc.

2011 . Garbage collector. concurrency etc.Status: Compilers gc (Ken Thompson). x86-64) and ARM. Good and improving libraries. Wednesday.k.a. 6g. implemented. a. June 15. 5g derived from the Plan 9 compiler model generates OK code very quickly not directly gcc-linkable gccgo (Ian Taylor) more familiar architecture generates good code not as quickly gcc-linkable Available for 32-bit and 64-bit x86 (amd64. 8g.

Basics Wednesday. June 15. 2011 .

2011 .Time for some code package main import "fmt" func main() { fmt. 世界\n") } Wednesday. June 15.Print("Hello.

Apologies for that. Wednesday. here comes a quick tour of the basics. familiar and therefore dull. 2011 .Language basics Assuming familiarity with other C-like languages. June 15. This will be mostly easy. The next two lectures contain the fun stuff but we need to lay down the groundwork first.

no nesting */ // So is this. Source is UTF-8. Comments: /* This is a comment. carriage return. June 15. newline. White space: blank. Identifiers are letters and numbers (plus '_') with "letter" and "number" defined by Unicode. 2011 . Wednesday. tab.Lexical structure Mostly traditional with modern details.

abc\t\` == "\\n\\. 2 bytes of UTF-8 Raw strings: `\n\.Literals C-like but numbers require no signedness or size markings (more about this soon): 23 0x0FF 1. June 15. but Unicode/UTF-8. both are bytes: "Hello. world\n" "\xFF" // 1 byte "\u00FF" // 1 Unicode char.234e7 C-like strings. Also \xNN always 2 digits.abc\\t\\" Wednesday. 2011 . \012 always 3.

i < 10. b int } Basic control structures are familiar: if a == b { return true } else { return false } for i = 0.Syntax overview Basically C-like with reversed types and declarations. but braces required. i++ { .. Wednesday. } Note: no parentheses. June 15.. 2011 . c *int // note difference from C var d []int type S struct { a. More about all this later. plus keywords to introduce each type of declaration. var a int var b.

Wednesday.Semicolons Semicolons terminate statements but: .lexer inserts them automatically at end of line if the previous token could end a statement.Note: much cleaner. Go code almost never has semicolons outside for and if clauses. simpler than JavaScript rule! Thus no semis needed in this program: package main const three = 3 var i int = three func main() { fmt. 2011 . i) } In practice. . June 15.Printf("%d\n".

These are all distinct types. int is not int32 even on a 32-bit machine. will be familiar: int int8 int16 int32 int64 uint uint8 = byte uint16 uint32 uint64 float32 float64 complex64 complex128 Also uintptr. Wednesday.Numeric types Numeric types are built in. June 15. No implicit conversions (but don't panic). 2011 . an integer big enough to store a pointer.

2011 . Pointers and integers are not booleans. June 15.Bool The usual boolean type. Wednesday.† † Consider (not Go): const bool False = "false". bool. The if statement etc. with values true and false (predefined constants). use boolean expressions.

Can reassign variables but not edit values.that is. Immutable. just like ints. Just as 3 is always 3.String The built-in type string represents immutable arrays of bytes . June 15. 2011 . Language has good support for string manipulation. Wednesday. String literals have type string. Strings are length-delimited not NUL-terminated. "hello" is always "hello". text.

Unary ^ is complement. Wednesday. June 15. 5 4 3 2 1 operators * / % << >> & &^ + .| ^ == != < <= > >= && || comments &^ is "bit clear" ^ is "xor" Operators that are also unary: & ! * + . 2011 .^ (plus <.Expressions Mostly C-like operators.for communication). Binary operators: Prec.

etc. require an unsigned shift count Non-surprises: assignment ops work as expected: += <<= &^= etc. *p++ is (*p)++ not *(p++)) &^ is new.are not expression operators (x++ is a statement. expressions generally look the same (indexing.Go vs. 2011 .) Wednesday. function call. handy in constant expressions << >> etc. C expressions Surprises for the C programmer: fewer precedence levels (should be easy) ^ instead of ~ (it's binary "exclusive or" made unary) ++ and -. not an expression. June 15.

2g\n".3i "hello.Sin(PI/8)) 7.Printf("%5. 2011 .Examples +x 23 + 3*x[i] x <= f() ^a >> b f() || g() x == y + 1 && <-ch > 0 x &^ 7 // x with the low 3 bits cleared fmt.234/x + 2. 2*math. June 15. " + "world" // concatenation // no C-like "a" "b" Wednesday.

2011 .more later. with syntax like a function call: uint8(intVar) int(float64Var) float64(intVar) // truncate to size // truncate fraction // convert to float64 Also some conversions to and from string: string(0x1234) string(sliceOfBytes) string(sliceOfInts) []byte("abc") []int("日本語") // // // // // == "\u1234" bytes -> bytes ints -> Unicode/UTF-8 bytes -> bytes Unicode/UTF-8 -> ints (Slices are related to arrays . June 15.) Wednesday.Numeric conversions Converting a numeric value from one type to another is a conversion.

234e5 1e2 3.2i 100 Wednesday. June 15.Constants Numeric constants are "ideal numbers": no size or sign. 077 // octal 0xFEEDBEEEEEEEEEEEEEEEEEEEEF 1 << 100 // hexadecimal There are integer and floating-point ideal numbers. hence no L or U or UL endings. 2011 // // // // floating-point floating-point imaginary floating-point integer . syntax of literal determines type: 1.

/2 3/2 3+2i // // // // floating floating integer: complex: point: 6.Constant Expressions Floating point and integer constants can be combined at will.5 1 3. 2*3. 2011 . The operations themselves also depend on the type.0+2.0i // high precision: const Ln2 = 0.69314718055994530941723212145817656807 const Log2E = 1/Ln2 // accurate reciprocal Representation is "big enough" (1024 bits now). June 15.14 3. Wednesday.28 point: 1. with the type of the resulting expression determined by the type of the constants.

5 can't be represented Wednesday.5) // // // // // bad: -1 can't be represented OK bad: 350 can't be represented OK: 35 bad: 3. 2011 .0) uint8(3.Sin(1) // float syntax OK here Constants must be representable in their type.Consequences of ideal numbers The language permits the use of constants without explicit conversion if the value can be represented (there's no conversion necessary. June 15. Example: ^0 is -1 which is not in range 0-255. the value is OK): var million int = 1e6 math. uint8(^0) ^uint8(0) uint8(350) uint8(35.

Also functions read better and are consistent with other declarations. Wednesday. y int } func sum(a. June 15./7. b int) int { return a + b } Why are they reversed? Earlier example: var p.Declarations Declarations are introduced by a keyword (var. q *int Both p and q have type *int. type Point struct { x. And there's another reason. coming up. type. const. 2011 . func) and are reversed compared to C: var i int const PI = 22.

floater. m uint64 = 1. June 15. 2 nanoseconds int64 = 1e9 // float64 constant! inter. var var var var var var i int j = 365. 2. "hi" Wednesday. Initializers must match variables (and types!).0. They may have a type or an initialization expression.Var Variable declarations are introduced by var. stringer = 1.245 k int = 0 l. 2011 . one or both must be present.

var but not func. 2 nanoseconds int64 = 1e9 inter. Group with parens: var ( i int j = 356.Distributing var Annoying to type var all the time. type. 2.0.245 k int = 0 l. m uint64 = 1. June 15. "hi" ) Applies to const. stringer = 1. floater. Wednesday. 2011 .

) The type is that of the value (for ideal numbers. d. June 15. e := 1. c.) a. Wednesday.The := "short declaration" Within functions (only). accordingly.0. "three". FOUR. b. declarations of the form var v = value can be shortened to v := value (Another reason for the name/type reversal. 2. get int or float64 or complex128. 2011 . 5e0i These are used a lot and are available in places such as for loop initializers.

2. 3 Thursday. Saturday = 4.Const Constant declarations are introduced by const. const AccuratePi float64 = 355. "veg" const ( Monday. Friday. 6 ) Wednesday. two. parsnip = "meat". 5. Wednesday = 1. evaluated at compile time. They must have a "constant expression"./7. 2011 . as initializer and may have an optional type specifier./113 const beef. June 15. 2. const Pi = 22. Tuesday.

1 // 1.Iota Constant declarations can use the counter iota. June 15. 4 . 1<<iota loc1. 2011 // 0. bit0 uint32 = iota. 2 // 2. const ( loc0. which starts at 0 in each const block and increments at each implicit semicolon (end of line). bit1 loc2. const ( Monday = iota Tuesday = iota ) // 0 // 1 Shorthand: Previous type and expressions repeat. bit2 ) Wednesday.

June 15. b int) int type SliceOfIntPointers []*int We'll come back to functions a little later. We'll learn more about types later but here are some examples: type Point struct { x. Wednesday. z float64 name string } type Operator func(a. y.Type Type declarations are introduced by type. 2011 .

var p *Point = new(Point) v := new(int) // v has type *int Later we'll see how to build slices and such. 2011 . Wednesday. June 15.New The built-in function new allocates memory. similar to C++. Returns a pointer to the allocated object. There is no delete or free. Go has garbage collection. with type as argument. Syntax is like a function call.

b = b.Assignment Assignment is easy and familiar: a = b But multiple assignment works too: x. error := Write(buf) Wednesday. a // swap Functions can return multiple values (details later): nbytes. f3() a. f2(). 2011 . z = f1(). y. June 15.

Wednesday. but braces mandatory. 2011 . no parentheses. Go has if. if. for and switch (plus one more to appear later).Control structures Similar to C. As stated before. but different in significant ways. For instance. They are quite regular when seen as a set. June 15. for and switch all accept initialization statements.

Forms of control structures
Details follow but in general: The if and switch statements come in 1- and 2-element forms, described below. The for loop has 1- and 3-element forms: single-element is C's while:
for a {}

triple-element is C's for:
for a;b;c {}

In any of these forms, any element can be empty.
Wednesday, June 15, 2011

If
Basic form is familiar, but no dangling else problem:
if x < 5 { less() } if x < 5 { less() } else if x == 5 { equal() }

Initialization statement allowed; requires semicolon.
if v := f(); v < 10 { fmt.Printf("%d less than 10\n", v) } else { fmt.Printf("%d not less than 10\n", v) }

Useful with multivariate functions:
if n, err = fd.Write(buf); err != nil { ... }

Missing condition means true, which is not too useful in this context but handy in for, switch.
Wednesday, June 15, 2011

For
Basic form is familiar:
for i := 0; i < 10; i++ { ... }

Missing condition means true:
for ;; { fmt.Printf("looping forever") }

But you can leave out the semis too:
for { fmt.Printf("Mine! ") }

Don't forget multivariate assigments:
for i,j := 0,N; i < j; i,j = i+1,j-1 {...}

(There's no comma operator as in C.)
Wednesday, June 15, 2011

instead.5.expressions need not be constant or even int.no automatic fall through . . But there are important syntactic and semantic differences: .multiple cases can be comma-separated switch count%7 { case 4. fallthrough case 1: a *= v. June 15.6: error() case 3: a *= v. lexically last statement can be fallthrough . 2011 . fallthrough case 0: return a*v } Wednesday.Switch details Switches are somewhat similar to C's. fallthrough case 2: a *= v.

Printf("0") default: fmt.Switch Go's switch is more powerful than C's. { . 2011 . } Wednesday. b := x[i].. Familiar form: switch a { case 0: fmt.. y[j]. b := x[i]. y[j] switch { case a < b: return -1 case a == b: return 0 case a > b: return 1 } or switch a. June 15.Printf("non-zero") } The expressions can be any type and a missing switch expression means true. Result: if-else chain: a.

June 15. 1. i++ { switch f(i) { case 0. there is a goto. i < 10. continue. The break and continue statements work as in C.Break. They may specify a label to affect an outer structure: Loop: for i := 0. etc. Wednesday. 2: break Loop } g(i) } Yes Ken. 2011 .

2011 . func square(f float64) float64 { return f*f } A function can return multiple values.Functions Functions are introduced by the func keyword. The return does as you expect. the return types are a parenthesized list. June 15. Return type.Sqrt(f). if any. true } return 0. If so. bool) { if f >= 0 { return math. comes after parameters. false } Wednesday. func MySqrt(f float64) (float64.

// Don't care about boolean from MySqrt. _ (underscore).The blank identifier What if you care only about the first value returned by MySqrt? Still need to put the second one somewhere. can always be assigned any value. June 15. _ = MySqrt(foo()) Handy in other contexts still to be presented. Predeclared. Solution: the blank identifier. which is discarded. val. 2011 . Wednesday.

Functions with result variables The result "parameters" are actual variables you can use if you name them. ok bool) { if f >= 0 { v. false etc. more in a sec). func MySqrt(f float64) (v float64.Sqrt(f).ok = 0.ok = math. true } else { v. according to type. true } return v.Sqrt(f).ok = math. func MySqrt(f float64) (v float64.ok } The result variables are initialized to "zero" (0.false } return v.ok } Wednesday. 0.0. ok bool) { if f >= 0 { v. 2011 . June 15.

ok = math.true } Wednesday.Sqrt(f). ok bool) { if f >= 0 { v. Two more versions of MySqrt: func MySqrt(f float64) (v float64.The empty return Finally. a return with no expressions returns the existing value of the result variables.Sqrt(f). 2011 . ok bool) { if f < 0 { return } // error case return math. June 15. true } return // must be explicit } func MySqrt(f float64) (v float64.

Printf("%d ". i++ { var v int fmt. channel. v) v = 5 } will print 0 0 0 0 0. nil pointer. etc. All variables are initialized upon execution of their declaration. map. zeroed struct. Without an initializing expression. slice. The loop for i := 0. The zero value depends on the type: numeric 0. boolean false. Wednesday. the "zero value" of the type is used. i < 5. empty string "".What was that about zero? All memory in Go is initialized. 2011 . June 15.

the function call happens upon return. func data(fileName string) string { f := os. June 15.Close() contents := io. Wednesday.ReadAll(f) return contents } Useful for closing fds. unlocking mutexes. The arguments are evaluated at the point of the defer. etc. 2011 .Defer The defer statement executes a function (or method) when the enclosing function returns.Open(fileName) defer f.

Wednesday. i) } } prints 4 3 2 1 0.Printf("%d ". June 15. i++ { defer fmt.One function invocation per defer Each defer that executes queues a function call to execute. so func f() { for i := 0. i < 5. in LIFO order. You can close all those fds or unlock those mutexes at the end. 2011 .

s) } func a() {  trace("a") defer untrace("a") fmt. 2011 .. June 15. s) } func untrace(s string) { fmt.Println("in b") a() } func main() { b() } But we can do it more neatly.Println("entering:".Println("in a") } func b() { trace("b") defer untrace("b") fmt.Println("leaving:". Wednesday.Tracing with defer func trace(s string) { fmt..

2011 .Println("in b") a() } func main() { b() } Wednesday. defer later func trace(s string) string {  fmt.Println("in a") } func b() {  defer un(trace("b")) fmt. s) return s } func un(s string) { fmt.Args evaluate now. s) } func a() {  defer un(trace("a")) fmt.Println("entering:". June 15.Println("leaving:".

i) } g(i) } } Wednesday. i < 10. functions can't be declared inside functions but function literals can be assigned to variables. 2011 . func f() { for i := 0. i++ { g := func(i int) { fmt. June 15.Function literals As in C.Printf("%d".

Function literals are closures Function literals are indeed closures.accumulating in f's x. func adder() (func(int) int) { var x int return func(delta int) int { x += delta return x } } f := adder() fmt. 2011 .Print(f(1)) fmt. June 15.Print(f(20)) fmt.Print(f(300)) Prints 1 21 321 . Wednesday.

2011 . June 15.Program construction Wednesday.

A package may be built from multiple source files.Itemname. which may use facilities from other packages. A Go program is created by linking together a set of packages. June 15. Wednesday. 2011 . Names in imported packages are accessed through a "qualified identifier": packagename.Packages A program is constructed as a "package".

a package clause (which package it's in).Source file structure Every source file contains: .an optional set of import declarations import "fmt" import myFmt "fmt" // use default name // use the name myFmt . 2011 . that name is the default name used by importers. package fmt .zero or more global or "package-level" declarations. June 15. Wednesday.

Print(hello) } // fmt is imported pkg's name Wednesday. 世界\n" func main() { fmt.A single-file package package main // this file is part of package "main" import "fmt" // this file uses package "fmt" const hello = "Hello. 2011 . June 15.

when main.main Each Go program contains a package called main and its main function. The main. is where execution starts.main returns. C++. after initialization. analogous with the global main() in C. 2011 . June 15.main function takes no arguments and returns no value. Wednesday. The program exits immediately and successfully .main and main.

June 15. i++ { fmt. etc.Args) < 2 { // length of argument slice os.The os package Package os provides Exit and access to file I/O.Exit(0) Wednesday. 2011 . i.Printf("arg %d: %s\n". i < len(os.Exit(1) } for i := 1.Args). os.Args[i]) } } // falling off end == os. // A version of echo(1) package main import ( "fmt" "os" ) func main() { if len(os. command-line arguments.

June 15. types. static. public. types. functions. all global variables. const hello = "you smell" const Hello = "you smell nice" const _Bye = "stinko!" // package visible // globally visible // _ is not upper Very different from C/C++: no extern. Wednesday. constants. 2011 . plus methods and structure fields for global variables and types. For clients (importers) of the package.Global and package scope Within a package. and constants are visible from all the package's source files. functions. names must be upper case to be visible: global variables. private.

main: 1) A global declaration with an initializer 2) Inside an init() function.Initialization Two ways to initialize global variables before execution of main. June 15. Initialization is always single-threaded. of which there may be any number in each source file. Wednesday. Package dependency guarantees correct execution order. 2011 .

Pi // decl computes twoPi func main() { fmt.283185307179586 Wednesday. June 15. 2011 .Initialization example package transcendental import "math" var Pi float64 func init() { Pi = 4*math. twoPi) } ==== Output: 2*Pi = 6.Printf("2*Pi = %g\n".Atan(1) // init function computes Pi } ==== package main import ( "fmt" "transcendental" ) var twoPi = 2*transcendental.

and the files within them. Go-specific tool is coming.Package and program construction To build a program. Ignoring tests. Wednesday. the packages. Within a package.go Usually we use make. 2011 . the source files must all be compiled together. and conventionally each directory contains one package. Package dependencies determine the order in which to build packages. June 15. cd mypackage 6g *. The package is compiled as a unit. must be compiled in the correct order.

go print.go print. June 15..go format.go format. % make clean. see sources. Makefiles are written using helpers called Make..pkg and so on. % make # hand-written but trivial % ls Makefile _go_.. Wednesday.. make ..Building the fmt package % pwd /Users/r/go/src/pkg/fmt % ls Makefile fmt_test.go # .6 _obj fmt_test.go # .. 2011 . Objects are placed into the subdirectory _obj.

gotest. Those functions should have signature func TestXxx(t *testing. 2011 .go. Wednesday. give the files names of the form *_test. June 15. error reporting. Within those files.Testing To test a package. global functions with names starting with Test[^a-z] will be run by the testing tool. benchmarking. write a set of Go source files within the same package.T) The testing package provides support for logging.

i < len(flagtests)." + " want %q". tt.T) { var flagprinter flagPrinter for i := 0.in.obvious syntax.out { // method call coming up . 2011 . not main import ( "testing" ) func TestFlagParser(t *testing.Errorf("Sprintf(%q.out) } } } Wednesday. s. June 15.An example test Interesting pieces from fmt_test. t.go: package fmt // package is fmt.in. i++ { tt := flagtests[i] s := Sprintf(tt. tt. &flagprinter) if s != tt. &flagprinter) => %q.

PASS: fmt.TestStructPrinter --.00 seconds) # plus lots more PASS % Wednesday.TestSprintf (0.TestArrayPrinter --.PASS: fmt.go format.TestArrayPrinter (0.go === RUN fmt.go # .go print. does all *_test.PASS: fmt.a fmt_test.Testing: gotest % ls Makefile fmt.TestFlagParser --.TestFmtInterface --.00 seconds) === RUN fmt.go PASS wally=% gotest -v fmt_test.TestSprintf --.00 seconds) === RUN fmt..00 seconds) === RUN fmt. June 15.TestFlagParser (0.TestStructPrinter (0. % gotest # by default.TestFmtInterface (0.PASS: fmt.PASS: fmt.00 seconds) === RUN fmt.. 2011 .

B) and loop over b. 2011 . not main import ( "testing" ) func BenchmarkSprintfInt(b *testing. Here is a benchmark example from fmt_test.N.go: package fmt // package is fmt.An example benchmark Benchmarks have signature func BenchmarkXxxx(b *testing. i < b. June 15. i++ { Sprintf("%d".B) { for i := 0. testing package does the rest. 5) } } Wednesday.N.

BenchmarkSprintfEmpty 5000000 310 ns/op fmt_test. % Wednesday.BenchmarkSprintfInt 5000000 663 ns/op fmt_test.Benchmarking: gotest % gotest -bench=".BenchmarkSprintfIntInt 2000000 969 ns/op ..BenchmarkSprintfString 2000000 774 ns/op fmt_test." # regular expression identifies which fmt_test. 2011 .. June 15.

June 15. Printf Compile. Atof. String Logger. Read. The set of libraries is modest but growing. Pipe Bool. flag event logging log regular expressions regexp HTML. 2011 . Match Parse.Libraries Libraries are just packages. Itoa Copy. Some examples: Package Purpose Examples Printf. etc. Scanf Open. Buffer formatted I/O fmt OS interface os strconv numbers <-> strings generic I/O io flags: --help etc. template byte arrays bytes Wednesday. Execute Compare. Write Atoi.

Sprint. "\n") fmt.writes to os.Println(1. Fprintln .Print(1. adds spaces.print to standard output Sprintf . " ".no format. 2011 . June 15. final \n fmt. 2. Sprintln.5.no format Println. 2.Printf("%d %d %g\n". Fprint .5) fmt.returns a string Fprintf . 3. 3. " ". 3.A little more about fmt The fmt package contains familiar names in initial caps: Printf .5) Each produces the same result: "1 2 3. (tomorrow) but also Print. 2.Stderr etc.5\n" Wednesday. 1.

Command line or web tool pulls them out. Link: http://golang. 2011 .org/pkg/ Command: % godoc fmt % godoc fmt Printf Wednesday. June 15.Library documentation Source code contains comments.

June 15. 2011 .Exercise Wednesday.

Wednesday. Write a package to implement it.html You all know what the Fibonacci series is.see http://golang. Write a gotest test for your package. June 15. Integers? Floats? Strings? Up to you. There should be a function to get the next value. (You don't have structs yet. make the operation settable by a function provided by the user.Exercise: Day 1 Set up a Go environment . 2011 .org/doc/install. can you find a way to save state without globals?) But instead of addition.

Next lesson Composite types Methods Interfaces Wednesday. 2011 . June 15.

2011 .com (updated June 2011) Wednesday. June 15.The Go Programming Language Part 1 Rob Pike r@google.

Sign up to vote on this title
UsefulNot useful