{"generics":{"Title":"Generics","Description":"Go supports generic programming using type parameters. This lesson shows some examples for employing generics in your code.","Pages":[{"Title":"Type parameters","Content":"\n \u003ch2\u003eType parameters\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go functions can be written to work on multiple types using type parameters. The\n\n\n type parameters of a function appear between brackets, before the function\u0026#39;s\n\n\n arguments.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003efunc Index[T comparable](s []T, x T) int\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n This declaration means that \u003ccode\u003es\u003c/code\u003e is a slice of any type \u003ccode\u003eT\u003c/code\u003e that fulfills the\n\n\n built-in constraint \u003ccode\u003ecomparable\u003c/code\u003e. \u003ccode\u003ex\u003c/code\u003e is also a value of the same type.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003ecomparable\u003c/code\u003e is a useful constraint that makes it possible to use the \u003ccode\u003e==\u003c/code\u003e and\n\n\n \u003ccode\u003e!=\u003c/code\u003e operators on values of the type. In this example, we use it to compare a\n\n\n value to all slice elements until a match is found. This \u003ccode\u003eIndex\u003c/code\u003e function works\n\n\n for any type that supports comparison.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"index.go","Content":"package main\n\nimport \"fmt\"\n\n// Index returns the index of x in s, or -1 if not found.\nfunc Index[T comparable](s []T, x T) int {\n\tfor i, v := range s {\n\t\t// v and x are type T, which has the comparable\n\t\t// constraint, so we can use == here.\n\t\tif v == x {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc main() {\n\t// Index works on a slice of ints\n\tsi := []int{10, 20, 15, -10}\n\tfmt.Println(Index(si, 15))\n\n\t// Index also works on a slice of strings\n\tss := []string{\"foo\", \"bar\", \"baz\"}\n\tfmt.Println(Index(ss, \"hello\"))\n}\n","Hash":"hA/jRsl39c12HDmaWx+0jqM1/T4="}]},{"Title":"Generic types","Content":"\n \u003ch2\u003eGeneric types\u003c/h2\u003e\n \n \n \u003cp\u003e\n In addition to generic functions, Go also supports generic types. A type can\n\n\n be parameterized with a type parameter, which could be useful for implementing\n\n\n generic data structures.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This example demonstrates a simple type declaration for a singly-linked list\n\n\n holding any type of value.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n As an exercise, add some functionality to this list implementation.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"list.go","Content":"package main\n\n// List represents a singly-linked list that holds\n// values of any type.\ntype List[T any] struct {\n\tnext *List[T]\n\tval T\n}\n\nfunc main() {\n}\n","Hash":"gXUxK6wdA4U2hDgZ76E8SbK4C5s="}]},{"Title":"Congratulations!","Content":"\n \u003ch2\u003eCongratulations!\u003c/h2\u003e\n \n \n \u003cp\u003e\n You finished this lesson!\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can go back to the list of \u003ca href=\"/tour/list\" target=\"_self\"\u003emodules\u003c/a\u003e to find what to learn next, or continue with the \u003ca href=\"javascript:click(\u0026#39;.next-page\u0026#39;)\" target=\"_self\"\u003enext lesson\u003c/a\u003e.\n \u003c/p\u003e\n \n\n","Files":[]}]} ,"methods":{"Title":"Methods and interfaces","Description":"This lesson covers methods and interfaces, the constructs that define objects and their behavior.","Pages":[{"Title":"Methods","Content":"\n \u003ch2\u003eMethods\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go does not have classes.\n\n\n However, you can define methods on types.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A method is a function with a special \u003ci\u003ereceiver\u003c/i\u003e argument.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The receiver appears in its own argument list between the \u003ccode\u003efunc\u003c/code\u003e keyword and\n\n\n the method name.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n In this example, the \u003ccode\u003eAbs\u003c/code\u003e method has a receiver of type \u003ccode\u003eVertex\u003c/code\u003e named \u003ccode\u003ev\u003c/code\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"methods.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc main() {\n\tv := Vertex{3, 4}\n\tfmt.Println(v.Abs())\n}\n","Hash":"Ri0Y1X1RvD4ysSICFlAD0YwiciM="}]},{"Title":"Methods are functions","Content":"\n \u003ch2\u003eMethods are functions\u003c/h2\u003e\n \n \n \u003cp\u003e\n Remember: a method is just a function with a receiver argument.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Here\u0026#39;s \u003ccode\u003eAbs\u003c/code\u003e written as a regular function with no change in functionality.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"methods-funcs.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc Abs(v Vertex) float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc main() {\n\tv := Vertex{3, 4}\n\tfmt.Println(Abs(v))\n}\n","Hash":"PKx6hnGY7gFDiHYMaaOuA0NgXYk="}]},{"Title":"Methods continued","Content":"\n \u003ch2\u003eMethods continued\u003c/h2\u003e\n \n \n \u003cp\u003e\n You can declare a method on non-struct types, too.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n In this example we see a numeric type \u003ccode\u003eMyFloat\u003c/code\u003e with an \u003ccode\u003eAbs\u003c/code\u003e method.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can only declare a method with a receiver whose type is defined in the same\n\n\n package as the method.\n\n\n You cannot declare a method with a receiver whose type is defined in another\n\n\n package (which includes the built-in types such as \u003ccode\u003eint\u003c/code\u003e).\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"methods-continued.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype MyFloat float64\n\nfunc (f MyFloat) Abs() float64 {\n\tif f \u003c 0 {\n\t\treturn float64(-f)\n\t}\n\treturn float64(f)\n}\n\nfunc main() {\n\tf := MyFloat(-math.Sqrt2)\n\tfmt.Println(f.Abs())\n}\n","Hash":"gNtDHNEf68ZV05Dn2/JqSHJO/CA="}]},{"Title":"Pointer receivers","Content":"\n \u003ch2\u003ePointer receivers\u003c/h2\u003e\n \n \n \u003cp\u003e\n You can declare methods with pointer receivers.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This means the receiver type has the literal syntax \u003ccode\u003e*T\u003c/code\u003e for some type \u003ccode\u003eT\u003c/code\u003e.\n\n\n (Also, \u003ccode\u003eT\u003c/code\u003e cannot itself be a pointer such as \u003ccode\u003e*int\u003c/code\u003e.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n For example, the \u003ccode\u003eScale\u003c/code\u003e method here is defined on \u003ccode\u003e*Vertex\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Methods with pointer receivers can modify the value to which the receiver\n\n\n points (as \u003ccode\u003eScale\u003c/code\u003e does here).\n\n\n Since methods often need to modify their receiver, pointer receivers are more\n\n\n common than value receivers.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Try removing the \u003ccode\u003e*\u003c/code\u003e from the declaration of the \u003ccode\u003eScale\u003c/code\u003e function on line 16\n\n\n and observe how the program\u0026#39;s behavior changes.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n With a value receiver, the \u003ccode\u003eScale\u003c/code\u003e method operates on a copy of the original\n\n\n \u003ccode\u003eVertex\u003c/code\u003e value.\n\n\n (This is the same behavior as for any other function argument.)\n\n\n The \u003ccode\u003eScale\u003c/code\u003e method must have a pointer receiver to change the \u003ccode\u003eVertex\u003c/code\u003e value\n\n\n declared in the \u003ccode\u003emain\u003c/code\u003e function.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"methods-pointers.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}\n\nfunc main() {\n\tv := Vertex{3, 4}\n\tv.Scale(10)\n\tfmt.Println(v.Abs())\n}\n","Hash":"fAxvljlTfE3Q8KGvdfBs1fyc8N8="}]},{"Title":"Pointers and functions","Content":"\n \u003ch2\u003ePointers and functions\u003c/h2\u003e\n \n \n \u003cp\u003e\n Here we see the \u003ccode\u003eAbs\u003c/code\u003e and \u003ccode\u003eScale\u003c/code\u003e methods rewritten as functions.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Again, try removing the \u003ccode\u003e*\u003c/code\u003e from line 16.\n\n\n Can you see why the behavior changes?\n\n\n What else did you need to change for the example to compile?\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (If you\u0026#39;re not sure, continue to the next page.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"methods-pointers-explained.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc Abs(v Vertex) float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc Scale(v *Vertex, f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}\n\nfunc main() {\n\tv := Vertex{3, 4}\n\tScale(\u0026v, 10)\n\tfmt.Println(Abs(v))\n}\n","Hash":"UkaipHI3vU5n36ImMygcCf5cug4="}]},{"Title":"Methods and pointer indirection","Content":"\n \u003ch2\u003eMethods and pointer indirection\u003c/h2\u003e\n \n \n \u003cp\u003e\n Comparing the previous two programs, you might notice that\n\n\n functions with a pointer argument must take a pointer:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar v Vertex\nScaleFunc(v, 5) // Compile error!\nScaleFunc(\u0026amp;v, 5) // OK\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n while methods with pointer receivers take either a value or a pointer as the\n\n\n receiver when they are called:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar v Vertex\nv.Scale(5) // OK\np := \u0026amp;v\np.Scale(10) // OK\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n For the statement \u003ccode\u003ev.Scale(5)\u003c/code\u003e, even though \u003ccode\u003ev\u003c/code\u003e is a value and not a pointer,\n\n\n the method with the pointer receiver is called automatically.\n\n\n That is, as a convenience, Go interprets the statement \u003ccode\u003ev.Scale(5)\u003c/code\u003e as\n\n\n \u003ccode\u003e(\u0026amp;v).Scale(5)\u003c/code\u003e since the \u003ccode\u003eScale\u003c/code\u003e method has a pointer receiver.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"indirection.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}\n\nfunc ScaleFunc(v *Vertex, f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}\n\nfunc main() {\n\tv := Vertex{3, 4}\n\tv.Scale(2)\n\tScaleFunc(\u0026v, 10)\n\n\tp := \u0026Vertex{4, 3}\n\tp.Scale(3)\n\tScaleFunc(p, 8)\n\n\tfmt.Println(v, p)\n}\n","Hash":"vkdr6283JVw0hF1pb2IlCOpFNks="}]},{"Title":"Methods and pointer indirection (2)","Content":"\n \u003ch2\u003eMethods and pointer indirection (2)\u003c/h2\u003e\n \n \n \u003cp\u003e\n The equivalent thing happens in the reverse direction.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Functions that take a value argument must take a value of that specific type:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar v Vertex\nfmt.Println(AbsFunc(v)) // OK\nfmt.Println(AbsFunc(\u0026amp;v)) // Compile error!\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n while methods with value receivers take either a value or a pointer as the\n\n\n receiver when they are called:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar v Vertex\nfmt.Println(v.Abs()) // OK\np := \u0026amp;v\nfmt.Println(p.Abs()) // OK\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n In this case, the method call \u003ccode\u003ep.Abs()\u003c/code\u003e is interpreted as \u003ccode\u003e(*p).Abs()\u003c/code\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"indirection-values.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc AbsFunc(v Vertex) float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc main() {\n\tv := Vertex{3, 4}\n\tfmt.Println(v.Abs())\n\tfmt.Println(AbsFunc(v))\n\n\tp := \u0026Vertex{4, 3}\n\tfmt.Println(p.Abs())\n\tfmt.Println(AbsFunc(*p))\n}\n","Hash":"uUoieKc4jMWBn0pBQ4TNmib2Zlk="}]},{"Title":"Choosing a value or pointer receiver","Content":"\n \u003ch2\u003eChoosing a value or pointer receiver\u003c/h2\u003e\n \n \n \u003cp\u003e\n There are two reasons to use a pointer receiver.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The first is so that the method can modify the value that its receiver points to.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The second is to avoid copying the value on each method call.\n\n\n This can be more efficient if the receiver is a large struct, for example.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n In this example, both \u003ccode\u003eScale\u003c/code\u003e and \u003ccode\u003eAbs\u003c/code\u003e are methods with receiver type \u003ccode\u003e*Vertex\u003c/code\u003e,\n\n\n even though the \u003ccode\u003eAbs\u003c/code\u003e method needn\u0026#39;t modify its receiver.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n In general, all methods on a given type should have either value or pointer\n\n\n receivers, but not a mixture of both.\n\n\n (We\u0026#39;ll see why over the next few pages.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"methods-with-pointer-receivers.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}\n\nfunc (v *Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n\nfunc main() {\n\tv := \u0026Vertex{3, 4}\n\tfmt.Printf(\"Before scaling: %+v, Abs: %v\\n\", v, v.Abs())\n\tv.Scale(5)\n\tfmt.Printf(\"After scaling: %+v, Abs: %v\\n\", v, v.Abs())\n}\n","Hash":"wI65OTRFYWjK10SKGOf4dt++gH8="}]},{"Title":"Interfaces","Content":"\n \u003ch2\u003eInterfaces\u003c/h2\u003e\n \n \n \u003cp\u003e\n An \u003ci\u003einterface type\u003c/i\u003e is defined as a set of method signatures.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A value of interface type can hold any value that implements those methods.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eNote:\u003c/b\u003e There is an error in the example code on line 22.\n\n\n \u003ccode\u003eVertex\u003c/code\u003e (the value type) doesn\u0026#39;t implement \u003ccode\u003eAbser\u003c/code\u003e because\n\n\n the \u003ccode\u003eAbs\u003c/code\u003e method is defined only on \u003ccode\u003e*Vertex\u003c/code\u003e (the pointer type).\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"interfaces.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Abser interface {\n\tAbs() float64\n}\n\nfunc main() {\n\tvar a Abser\n\tf := MyFloat(-math.Sqrt2)\n\tv := Vertex{3, 4}\n\n\ta = f // a MyFloat implements Abser\n\ta = \u0026v // a *Vertex implements Abser\n\n\t// In the following line, v is a Vertex (not *Vertex)\n\t// and does NOT implement Abser.\n\ta = v\n\n\tfmt.Println(a.Abs())\n}\n\ntype MyFloat float64\n\nfunc (f MyFloat) Abs() float64 {\n\tif f \u003c 0 {\n\t\treturn float64(-f)\n\t}\n\treturn float64(f)\n}\n\ntype Vertex struct {\n\tX, Y float64\n}\n\nfunc (v *Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}\n","Hash":"3OoEceqBGQjIXrE7w1MK8wW7yzU="}]},{"Title":"Interfaces are implemented implicitly","Content":"\n \u003ch2\u003eInterfaces are implemented implicitly\u003c/h2\u003e\n \n \n \u003cp\u003e\n A type implements an interface by implementing its methods.\n\n\n There is no explicit declaration of intent, no \u0026#34;implements\u0026#34; keyword.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Implicit interfaces decouple the definition of an interface from its\n\n\n implementation, which could then appear in any package without prearrangement.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"interfaces-are-satisfied-implicitly.go","Content":"package main\n\nimport \"fmt\"\n\ntype I interface {\n\tM()\n}\n\ntype T struct {\n\tS string\n}\n\n// This method means type T implements the interface I,\n// but we don't need to explicitly declare that it does so.\nfunc (t T) M() {\n\tfmt.Println(t.S)\n}\n\nfunc main() {\n\tvar i I = T{\"hello\"}\n\ti.M()\n}\n","Hash":"9SSrQfjpROkzgOCerEmW39u7nLM="}]},{"Title":"Interface values","Content":"\n \u003ch2\u003eInterface values\u003c/h2\u003e\n \n \n \u003cp\u003e\n Under the hood, interface values can be thought of as a tuple of a value and a\n\n\n concrete type:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003e(value, type)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n An interface value holds a value of a specific underlying concrete type.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Calling a method on an interface value executes the method of the same name on\n\n\n its underlying type.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"interface-values.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype I interface {\n\tM()\n}\n\ntype T struct {\n\tS string\n}\n\nfunc (t *T) M() {\n\tfmt.Println(t.S)\n}\n\ntype F float64\n\nfunc (f F) M() {\n\tfmt.Println(f)\n}\n\nfunc main() {\n\tvar i I\n\n\ti = \u0026T{\"Hello\"}\n\tdescribe(i)\n\ti.M()\n\n\ti = F(math.Pi)\n\tdescribe(i)\n\ti.M()\n}\n\nfunc describe(i I) {\n\tfmt.Printf(\"(%v, %T)\\n\", i, i)\n}\n","Hash":"eiIEA+Gt4mqHxwJ7UVjixA/Lnic="}]},{"Title":"Interface values with nil underlying values","Content":"\n \u003ch2\u003eInterface values with nil underlying values\u003c/h2\u003e\n \n \n \u003cp\u003e\n If the concrete value inside the interface itself is nil,\n\n\n the method will be called with a nil receiver.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n In some languages this would trigger a null pointer exception,\n\n\n but in Go it is common to write methods that gracefully handle being called\n\n\n with a nil receiver (as with the method \u003ccode\u003eM\u003c/code\u003e in this example.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Note that an interface value that holds a nil concrete value is itself non-nil.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"interface-values-with-nil.go","Content":"package main\n\nimport \"fmt\"\n\ntype I interface {\n\tM()\n}\n\ntype T struct {\n\tS string\n}\n\nfunc (t *T) M() {\n\tif t == nil {\n\t\tfmt.Println(\"\u003cnil\u003e\")\n\t\treturn\n\t}\n\tfmt.Println(t.S)\n}\n\nfunc main() {\n\tvar i I\n\n\tvar t *T\n\ti = t\n\tdescribe(i)\n\ti.M()\n\n\ti = \u0026T{\"hello\"}\n\tdescribe(i)\n\ti.M()\n}\n\nfunc describe(i I) {\n\tfmt.Printf(\"(%v, %T)\\n\", i, i)\n}\n","Hash":"d1cP7OS65FGSVmmIKhXhW5Ffn2c="}]},{"Title":"Nil interface values","Content":"\n \u003ch2\u003eNil interface values\u003c/h2\u003e\n \n \n \u003cp\u003e\n A nil interface value holds neither value nor concrete type.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Calling a method on a nil interface is a run-time error because there is no\n\n\n type inside the interface tuple to indicate which \u003ci\u003econcrete\u003c/i\u003e method to call.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"nil-interface-values.go","Content":"package main\n\nimport \"fmt\"\n\ntype I interface {\n\tM()\n}\n\nfunc main() {\n\tvar i I\n\tdescribe(i)\n\ti.M()\n}\n\nfunc describe(i I) {\n\tfmt.Printf(\"(%v, %T)\\n\", i, i)\n}\n","Hash":"m1jbfiHj+IRAgnXILJjQBJV0WRo="}]},{"Title":"The empty interface","Content":"\n \u003ch2\u003eThe empty interface\u003c/h2\u003e\n \n \n \u003cp\u003e\n The interface type that specifies zero methods is known as the \u003ci\u003eempty interface\u003c/i\u003e:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003einterface{}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n An empty interface may hold values of any type.\n\n\n (Every type implements at least zero methods.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Empty interfaces are used by code that handles values of unknown type.\n\n\n For example, \u003ccode\u003efmt.Print\u003c/code\u003e takes any number of arguments of type \u003ccode\u003einterface{}\u003c/code\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"empty-interface.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar i interface{}\n\tdescribe(i)\n\n\ti = 42\n\tdescribe(i)\n\n\ti = \"hello\"\n\tdescribe(i)\n}\n\nfunc describe(i interface{}) {\n\tfmt.Printf(\"(%v, %T)\\n\", i, i)\n}\n","Hash":"4kA4LHru7y4jxvYduQKXrxssFu0="}]},{"Title":"Type assertions","Content":"\n \u003ch2\u003eType assertions\u003c/h2\u003e\n \n \n \u003cp\u003e\n A \u003ci\u003etype assertion\u003c/i\u003e provides access to an interface value\u0026#39;s underlying concrete value.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003et := i.(T)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n This statement asserts that the interface value \u003ccode\u003ei\u003c/code\u003e holds the concrete type \u003ccode\u003eT\u003c/code\u003e\n\n\n and assigns the underlying \u003ccode\u003eT\u003c/code\u003e value to the variable \u003ccode\u003et\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n If \u003ccode\u003ei\u003c/code\u003e does not hold a \u003ccode\u003eT\u003c/code\u003e, the statement will trigger a panic.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To \u003ci\u003etest\u003c/i\u003e whether an interface value holds a specific type,\n\n\n a type assertion can return two values: the underlying value\n\n\n and a boolean value that reports whether the assertion succeeded.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003et, ok := i.(T)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n If \u003ccode\u003ei\u003c/code\u003e holds a \u003ccode\u003eT\u003c/code\u003e, then \u003ccode\u003et\u003c/code\u003e will be the underlying value and \u003ccode\u003eok\u003c/code\u003e will be true.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n If not, \u003ccode\u003eok\u003c/code\u003e will be false and \u003ccode\u003et\u003c/code\u003e will be the zero value of type \u003ccode\u003eT\u003c/code\u003e,\n\n\n and no panic occurs.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Note the similarity between this syntax and that of reading from a map.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"type-assertions.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar i interface{} = \"hello\"\n\n\ts := i.(string)\n\tfmt.Println(s)\n\n\ts, ok := i.(string)\n\tfmt.Println(s, ok)\n\n\tf, ok := i.(float64)\n\tfmt.Println(f, ok)\n\n\tf = i.(float64) // panic\n\tfmt.Println(f)\n}\n","Hash":"pr1VboYZkIF99GtaIO2OF3F1slk="}]},{"Title":"Type switches","Content":"\n \u003ch2\u003eType switches\u003c/h2\u003e\n \n \n \u003cp\u003e\n A \u003ci\u003etype switch\u003c/i\u003e is a construct that permits several type assertions in series.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A type switch is like a regular switch statement, but the cases in a type\n\n\n switch specify types (not values), and those values are compared against\n\n\n the type of the value held by the given interface value.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eswitch v := i.(type) {\ncase T:\n // here v has type T\ncase S:\n // here v has type S\ndefault:\n // no match; here v has the same type as i\n}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n The declaration in a type switch has the same syntax as a type assertion \u003ccode\u003ei.(T)\u003c/code\u003e,\n\n\n but the specific type \u003ccode\u003eT\u003c/code\u003e is replaced with the keyword \u003ccode\u003etype\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This switch statement tests whether the interface value \u003ccode\u003ei\u003c/code\u003e\n\n\n holds a value of type \u003ccode\u003eT\u003c/code\u003e or \u003ccode\u003eS\u003c/code\u003e.\n\n\n In each of the \u003ccode\u003eT\u003c/code\u003e and \u003ccode\u003eS\u003c/code\u003e cases, the variable \u003ccode\u003ev\u003c/code\u003e will be of type\n\n\n \u003ccode\u003eT\u003c/code\u003e or \u003ccode\u003eS\u003c/code\u003e respectively and hold the value held by \u003ccode\u003ei\u003c/code\u003e.\n\n\n In the default case (where there is no match), the variable \u003ccode\u003ev\u003c/code\u003e is\n\n\n of the same interface type and value as \u003ccode\u003ei\u003c/code\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"type-switches.go","Content":"package main\n\nimport \"fmt\"\n\nfunc do(i interface{}) {\n\tswitch v := i.(type) {\n\tcase int:\n\t\tfmt.Printf(\"Twice %v is %v\\n\", v, v*2)\n\tcase string:\n\t\tfmt.Printf(\"%q is %v bytes long\\n\", v, len(v))\n\tdefault:\n\t\tfmt.Printf(\"I don't know about type %T!\\n\", v)\n\t}\n}\n\nfunc main() {\n\tdo(21)\n\tdo(\"hello\")\n\tdo(true)\n}\n","Hash":"rCrmEEtXHumb7jgXlgnkuwClmlA="}]},{"Title":"Stringers","Content":"\n \u003ch2\u003eStringers\u003c/h2\u003e\n \n \n \u003cp\u003e\n One of the most ubiquitous interfaces is \u003ca href=\"/pkg/fmt/#Stringer\" target=\"_self\"\u003e\u003ccode\u003eStringer\u003c/code\u003e\u003c/a\u003e defined by the \u003ca href=\"/pkg/fmt/\" target=\"_self\"\u003e\u003ccode\u003efmt\u003c/code\u003e\u003c/a\u003e package.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003etype Stringer interface {\n String() string\n}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n A \u003ccode\u003eStringer\u003c/code\u003e is a type that can describe itself as a string. The \u003ccode\u003efmt\u003c/code\u003e package\n\n\n (and many others) look for this interface to print values.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"stringer.go","Content":"package main\n\nimport \"fmt\"\n\ntype Person struct {\n\tName string\n\tAge int\n}\n\nfunc (p Person) String() string {\n\treturn fmt.Sprintf(\"%v (%v years)\", p.Name, p.Age)\n}\n\nfunc main() {\n\ta := Person{\"Arthur Dent\", 42}\n\tz := Person{\"Zaphod Beeblebrox\", 9001}\n\tfmt.Println(a, z)\n}\n","Hash":"yDPrm3LH5/ruqqZtQwyJqimSgis="}]},{"Title":"Exercise: Stringers","Content":"\n \u003ch2\u003eExercise: Stringers\u003c/h2\u003e\n \n \n \u003cp\u003e\n Make the \u003ccode\u003eIPAddr\u003c/code\u003e type implement \u003ccode\u003efmt.Stringer\u003c/code\u003e to print the address as\n\n\n a dotted quad.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n For instance, \u003ccode\u003eIPAddr{1, 2, 3, 4}\u003c/code\u003e should print as \u003ccode\u003e\u0026#34;1.2.3.4\u0026#34;\u003c/code\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-stringer.go","Content":"package main\n\nimport \"fmt\"\n\ntype IPAddr [4]byte\n\n// TODO: Add a \"String() string\" method to IPAddr.\n\nfunc main() {\n\thosts := map[string]IPAddr{\n\t\t\"loopback\": {127, 0, 0, 1},\n\t\t\"googleDNS\": {8, 8, 8, 8},\n\t}\n\tfor name, ip := range hosts {\n\t\tfmt.Printf(\"%v: %v\\n\", name, ip)\n\t}\n}\n","Hash":"6yJwu1CuXiC4ulEVUQfFXVtLSIU="}]},{"Title":"Errors","Content":"\n \u003ch2\u003eErrors\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go programs express error state with \u003ccode\u003eerror\u003c/code\u003e values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003eerror\u003c/code\u003e type is a built-in interface similar to \u003ccode\u003efmt.Stringer\u003c/code\u003e:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003etype error interface {\n Error() string\n}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n (As with \u003ccode\u003efmt.Stringer\u003c/code\u003e, the \u003ccode\u003efmt\u003c/code\u003e package looks for the \u003ccode\u003eerror\u003c/code\u003e interface when\n\n\n printing values.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Functions often return an \u003ccode\u003eerror\u003c/code\u003e value, and calling code should handle errors\n\n\n by testing whether the error equals \u003ccode\u003enil\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ei, err := strconv.Atoi(\u0026#34;42\u0026#34;)\nif err != nil {\n fmt.Printf(\u0026#34;couldn\u0026#39;t convert number: %v\\n\u0026#34;, err)\n return\n}\nfmt.Println(\u0026#34;Converted integer:\u0026#34;, i)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n A nil \u003ccode\u003eerror\u003c/code\u003e denotes success; a non-nil \u003ccode\u003eerror\u003c/code\u003e denotes failure.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"errors.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype MyError struct {\n\tWhen time.Time\n\tWhat string\n}\n\nfunc (e *MyError) Error() string {\n\treturn fmt.Sprintf(\"at %v, %s\",\n\t\te.When, e.What)\n}\n\nfunc run() error {\n\treturn \u0026MyError{\n\t\ttime.Now(),\n\t\t\"it didn't work\",\n\t}\n}\n\nfunc main() {\n\tif err := run(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n","Hash":"L0Wnwx4HpZxHa3I6ymeZsavC3Sc="}]},{"Title":"Exercise: Errors","Content":"\n \u003ch2\u003eExercise: Errors\u003c/h2\u003e\n \n \n \u003cp\u003e\n Copy your \u003ccode\u003eSqrt\u003c/code\u003e function from the \u003ca href=\"/tour/flowcontrol/8\" target=\"_self\"\u003eearlier exercise\u003c/a\u003e and modify it to return an \u003ccode\u003eerror\u003c/code\u003e value.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003eSqrt\u003c/code\u003e should return a non-nil error value when given a negative number, as it doesn\u0026#39;t support complex numbers.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Create a new type\n \u003c/p\u003e\n \n\n \n \u003cpre\u003etype ErrNegativeSqrt float64\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n and make it an \u003ccode\u003eerror\u003c/code\u003e by giving it a\n \u003c/p\u003e\n \n\n \n \u003cpre\u003efunc (e ErrNegativeSqrt) Error() string\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n method such that \u003ccode\u003eErrNegativeSqrt(-2).Error()\u003c/code\u003e returns \u003ccode\u003e\u0026#34;cannot Sqrt negative number: -2\u0026#34;\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eNote:\u003c/b\u003e A call to \u003ccode\u003efmt.Sprint(e)\u003c/code\u003e inside the \u003ccode\u003eError\u003c/code\u003e method will send the program into an infinite loop. You can avoid this by converting \u003ccode\u003ee\u003c/code\u003e first: \u003ccode\u003efmt.Sprint(float64(e))\u003c/code\u003e. Why?\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Change your \u003ccode\u003eSqrt\u003c/code\u003e function to return an \u003ccode\u003eErrNegativeSqrt\u003c/code\u003e value when given a negative number.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-errors.go","Content":"package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc Sqrt(x float64) (float64, error) {\n\treturn 0, nil\n}\n\nfunc main() {\n\tfmt.Println(Sqrt(2))\n\tfmt.Println(Sqrt(-2))\n}\n","Hash":"EKinkD7zz+EfKluJKZzDvhrrNEE="}]},{"Title":"Readers","Content":"\n \u003ch2\u003eReaders\u003c/h2\u003e\n \n \n \u003cp\u003e\n The \u003ccode\u003eio\u003c/code\u003e package specifies the \u003ccode\u003eio.Reader\u003c/code\u003e interface,\n\n\n which represents the read end of a stream of data.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The Go standard library contains \u003ca href=\"https://cs.opensource.google/search?q=Read%5C(%5Cw%2B%5Cs%5C%5B%5C%5Dbyte%5C)\u0026amp;ss=go%2Fgo\" target=\"_blank\"\u003emany implementations\u003c/a\u003e of this interface, including files, network connections, compressors, ciphers, and others.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003eio.Reader\u003c/code\u003e interface has a \u003ccode\u003eRead\u003c/code\u003e method:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003efunc (T) Read(b []byte) (n int, err error)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003eRead\u003c/code\u003e populates the given byte slice with data and returns the number of bytes\n\n\n populated and an error value. It returns an \u003ccode\u003eio.EOF\u003c/code\u003e error when the stream\n\n\n ends.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The example code creates a\n\n\n \u003ca href=\"/pkg/strings/#Reader\" target=\"_self\"\u003e\u003ccode\u003estrings.Reader\u003c/code\u003e\u003c/a\u003e\n\n\n and consumes its output 8 bytes at a time.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"reader.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\nfunc main() {\n\tr := strings.NewReader(\"Hello, Reader!\")\n\n\tb := make([]byte, 8)\n\tfor {\n\t\tn, err := r.Read(b)\n\t\tfmt.Printf(\"n = %v err = %v b = %v\\n\", n, err, b)\n\t\tfmt.Printf(\"b[:n] = %q\\n\", b[:n])\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n}\n","Hash":"RqUBLmjOXf3/eBY7ah885QcwgNY="}]},{"Title":"Exercise: Readers","Content":"\n \u003ch2\u003eExercise: Readers\u003c/h2\u003e\n \n \n \u003cp\u003e\n Implement a \u003ccode\u003eReader\u003c/code\u003e type that emits an infinite stream of the ASCII character\n\n\n \u003ccode\u003e\u0026#39;A\u0026#39;\u003c/code\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-reader.go","Content":"package main\n\nimport \"golang.org/x/tour/reader\"\n\ntype MyReader struct{}\n\n// TODO: Add a Read([]byte) (int, error) method to MyReader.\n\nfunc main() {\n\treader.Validate(MyReader{})\n}\n","Hash":"6sW4PjGtNz4iki66R8mgRBai0h8="}]},{"Title":"Exercise: rot13Reader","Content":"\n \u003ch2\u003eExercise: rot13Reader\u003c/h2\u003e\n \n \n \u003cp\u003e\n A common pattern is an \u003ca href=\"/pkg/io/#Reader\" target=\"_self\"\u003eio.Reader\u003c/a\u003e that wraps another \u003ccode\u003eio.Reader\u003c/code\u003e, modifying the stream in some way.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n For example, the \u003ca href=\"/pkg/compress/gzip/#NewReader\" target=\"_self\"\u003egzip.NewReader\u003c/a\u003e function takes an \u003ccode\u003eio.Reader\u003c/code\u003e (a stream of compressed data) and returns a \u003ccode\u003e*gzip.Reader\u003c/code\u003e that also implements \u003ccode\u003eio.Reader\u003c/code\u003e (a stream of the decompressed data).\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Implement a \u003ccode\u003erot13Reader\u003c/code\u003e that implements \u003ccode\u003eio.Reader\u003c/code\u003e and reads from an \u003ccode\u003eio.Reader\u003c/code\u003e, modifying the stream by applying the \u003ca href=\"https://en.wikipedia.org/wiki/ROT13\" target=\"_blank\"\u003erot13\u003c/a\u003e substitution cipher to all alphabetical characters.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003erot13Reader\u003c/code\u003e type is provided for you.\n\n\n Make it an \u003ccode\u003eio.Reader\u003c/code\u003e by implementing its \u003ccode\u003eRead\u003c/code\u003e method.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-rot-reader.go","Content":"package main\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype rot13Reader struct {\n\tr io.Reader\n}\n\nfunc main() {\n\ts := strings.NewReader(\"Lbh penpxrq gur pbqr!\")\n\tr := rot13Reader{s}\n\tio.Copy(os.Stdout, \u0026r)\n}\n","Hash":"XPnNEi79ZGAvQXBKmWMSdJasF8g="}]},{"Title":"Images","Content":"\n \u003ch2\u003eImages\u003c/h2\u003e\n \n \n \u003cp\u003e\n \u003ca href=\"/pkg/image/#Image\" target=\"_self\"\u003ePackage image\u003c/a\u003e defines the \u003ccode\u003eImage\u003c/code\u003e interface:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003epackage image\n\ntype Image interface {\n ColorModel() color.Model\n Bounds() Rectangle\n At(x, y int) color.Color\n}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eNote\u003c/b\u003e: the \u003ccode\u003eRectangle\u003c/code\u003e return value of the \u003ccode\u003eBounds\u003c/code\u003e method is actually an\n\n\n \u003ca href=\"/pkg/image/#Rectangle\" target=\"_self\"\u003e\u003ccode\u003eimage.Rectangle\u003c/code\u003e\u003c/a\u003e, as the\n\n\n declaration is inside package \u003ccode\u003eimage\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (See \u003ca href=\"/pkg/image/#Image\" target=\"_self\"\u003ethe documentation\u003c/a\u003e for all the details.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003ecolor.Color\u003c/code\u003e and \u003ccode\u003ecolor.Model\u003c/code\u003e types are also interfaces, but we\u0026#39;ll ignore that by using the predefined implementations \u003ccode\u003ecolor.RGBA\u003c/code\u003e and \u003ccode\u003ecolor.RGBAModel\u003c/code\u003e. These interfaces and types are specified by the \u003ca href=\"/pkg/image/color/\" target=\"_self\"\u003eimage/color package\u003c/a\u003e\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"images.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n)\n\nfunc main() {\n\tm := image.NewRGBA(image.Rect(0, 0, 100, 100))\n\tfmt.Println(m.Bounds())\n\tfmt.Println(m.At(0, 0).RGBA())\n}\n","Hash":"V0zUjPfdo4VBN4QyphuqbhHFKR8="}]},{"Title":"Exercise: Images","Content":"\n \u003ch2\u003eExercise: Images\u003c/h2\u003e\n \n \n \u003cp\u003e\n Remember the \u003ca href=\"/tour/moretypes/18\" target=\"_self\"\u003epicture generator\u003c/a\u003e you wrote earlier? Let\u0026#39;s write another one, but this time it will return an implementation of \u003ccode\u003eimage.Image\u003c/code\u003e instead of a slice of data.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Define your own \u003ccode\u003eImage\u003c/code\u003e type, implement \u003ca href=\"/pkg/image/#Image\" target=\"_self\"\u003ethe necessary methods\u003c/a\u003e, and call \u003ccode\u003epic.ShowImage\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003eBounds\u003c/code\u003e should return a \u003ccode\u003eimage.Rectangle\u003c/code\u003e, like \u003ccode\u003eimage.Rect(0, 0, w, h)\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003eColorModel\u003c/code\u003e should return \u003ccode\u003ecolor.RGBAModel\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003eAt\u003c/code\u003e should return a color; the value \u003ccode\u003ev\u003c/code\u003e in the last picture generator corresponds to \u003ccode\u003ecolor.RGBA{v, v, 255, 255}\u003c/code\u003e in this one.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-images.go","Content":"package main\n\nimport \"golang.org/x/tour/pic\"\n\ntype Image struct{}\n\nfunc main() {\n\tm := Image{}\n\tpic.ShowImage(m)\n}\n","Hash":"Dwmfm74h39vycGjq0+RRDHA66CM="}]},{"Title":"Congratulations!","Content":"\n \u003ch2\u003eCongratulations!\u003c/h2\u003e\n \n \n \u003cp\u003e\n You finished this lesson!\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can go back to the list of \u003ca href=\"/tour/list\" target=\"_self\"\u003emodules\u003c/a\u003e to find what to learn next, or continue with the \u003ca href=\"javascript:click(\u0026#39;.next-page\u0026#39;)\" target=\"_self\"\u003enext lesson\u003c/a\u003e.\n \u003c/p\u003e\n \n\n","Files":[]}]} ,"moretypes":{"Title":"More types: structs, slices, and maps.","Description":"Learn how to define types based on existing ones: this lesson covers structs, arrays, slices, and maps.","Pages":[{"Title":"Pointers","Content":"\n \u003ch2\u003ePointers\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go has pointers.\n\n\n A pointer holds the memory address of a value.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The type \u003ccode\u003e*T\u003c/code\u003e is a pointer to a \u003ccode\u003eT\u003c/code\u003e value. Its zero value is \u003ccode\u003enil\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar p *int\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003e\u0026amp;\u003c/code\u003e operator generates a pointer to its operand.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ei := 42\np = \u0026amp;i\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003e*\u003c/code\u003e operator denotes the pointer\u0026#39;s underlying value.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003efmt.Println(*p) // read i through the pointer p\n*p = 21 // set i through the pointer p\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n This is known as \u0026#34;dereferencing\u0026#34; or \u0026#34;indirecting\u0026#34;.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Unlike C, Go has no pointer arithmetic.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"pointers.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ti, j := 42, 2701\n\n\tp := \u0026i // point to i\n\tfmt.Println(*p) // read i through the pointer\n\t*p = 21 // set i through the pointer\n\tfmt.Println(i) // see the new value of i\n\n\tp = \u0026j // point to j\n\t*p = *p / 37 // divide j through the pointer\n\tfmt.Println(j) // see the new value of j\n}\n","Hash":"i+Ht96dGPTEcg2FJF7q5RseXBDI="}]},{"Title":"Structs","Content":"\n \u003ch2\u003eStructs\u003c/h2\u003e\n \n \n \u003cp\u003e\n A \u003ccode\u003estruct\u003c/code\u003e is a collection of fields.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"structs.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tX int\n\tY int\n}\n\nfunc main() {\n\tfmt.Println(Vertex{1, 2})\n}\n","Hash":"Ogg/+09TFU5IkZ2RcCCZsHf+2fo="}]},{"Title":"Struct Fields","Content":"\n \u003ch2\u003eStruct Fields\u003c/h2\u003e\n \n \n \u003cp\u003e\n Struct fields are accessed using a dot.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"struct-fields.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tX int\n\tY int\n}\n\nfunc main() {\n\tv := Vertex{1, 2}\n\tv.X = 4\n\tfmt.Println(v.X)\n}\n","Hash":"ghPOKvMr3gvwG4M0Z4zg3Bpwgpg="}]},{"Title":"Pointers to structs","Content":"\n \u003ch2\u003ePointers to structs\u003c/h2\u003e\n \n \n \u003cp\u003e\n Struct fields can be accessed through a struct pointer.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To access the field \u003ccode\u003eX\u003c/code\u003e of a struct when we have the struct pointer \u003ccode\u003ep\u003c/code\u003e we could\n\n\n write \u003ccode\u003e(*p).X\u003c/code\u003e.\n\n\n However, that notation is cumbersome, so the language permits us instead to\n\n\n write just \u003ccode\u003ep.X\u003c/code\u003e, without the explicit dereference.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"struct-pointers.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tX int\n\tY int\n}\n\nfunc main() {\n\tv := Vertex{1, 2}\n\tp := \u0026v\n\tp.X = 1e9\n\tfmt.Println(v)\n}\n","Hash":"m85TYBjwWGtTynTtt1+951KkQro="}]},{"Title":"Struct Literals","Content":"\n \u003ch2\u003eStruct Literals\u003c/h2\u003e\n \n \n \u003cp\u003e\n A struct literal denotes a newly allocated struct value by listing the values of its fields.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can list just a subset of fields by using the \u003ccode\u003eName:\u003c/code\u003e syntax. (And the order of named fields is irrelevant.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The special prefix \u003ccode\u003e\u0026amp;\u003c/code\u003e returns a pointer to the struct value.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"struct-literals.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tX, Y int\n}\n\nvar (\n\tv1 = Vertex{1, 2} // has type Vertex\n\tv2 = Vertex{X: 1} // Y:0 is implicit\n\tv3 = Vertex{} // X:0 and Y:0\n\tp = \u0026Vertex{1, 2} // has type *Vertex\n)\n\nfunc main() {\n\tfmt.Println(v1, p, v2, v3)\n}\n","Hash":"EFcXlUPwNHEgPnj9+DjstTj4J+M="}]},{"Title":"Arrays","Content":"\n \u003ch2\u003eArrays\u003c/h2\u003e\n \n \n \u003cp\u003e\n The type \u003ccode\u003e[n]T\u003c/code\u003e is an array of \u003ccode\u003en\u003c/code\u003e values of type \u003ccode\u003eT\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The expression\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar a [10]int\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n declares a variable \u003ccode\u003ea\u003c/code\u003e as an array of ten integers.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n An array\u0026#39;s length is part of its type, so arrays cannot be resized.\n\n\n This seems limiting, but don\u0026#39;t worry;\n\n\n Go provides a convenient way of working with arrays.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"array.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar a [2]string\n\ta[0] = \"Hello\"\n\ta[1] = \"World\"\n\tfmt.Println(a[0], a[1])\n\tfmt.Println(a)\n\n\tprimes := [6]int{2, 3, 5, 7, 11, 13}\n\tfmt.Println(primes)\n}\n","Hash":"XKucdSMaX+YMKsilkKDJ0Dpqosw="}]},{"Title":"Slices","Content":"\n \u003ch2\u003eSlices\u003c/h2\u003e\n \n \n \u003cp\u003e\n An array has a fixed size.\n\n\n A slice, on the other hand, is a dynamically-sized,\n\n\n flexible view into the elements of an array.\n\n\n In practice, slices are much more common than arrays.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The type \u003ccode\u003e[]T\u003c/code\u003e is a slice with elements of type \u003ccode\u003eT\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A slice is formed by specifying two indices, a low and\n\n\n high bound, separated by a colon:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ea[low : high]\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n This selects a half-open range which includes the first\n\n\n element, but excludes the last one.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The following expression creates a slice which includes\n\n\n elements 1 through 3 of \u003ccode\u003ea\u003c/code\u003e:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ea[1:4]\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"slices.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tprimes := [6]int{2, 3, 5, 7, 11, 13}\n\n\tvar s []int = primes[1:4]\n\tfmt.Println(s)\n}\n","Hash":"tGAAck8epB4KGh6NPwHBhTpmQPM="}]},{"Title":"Slices are like references to arrays","Content":"\n \u003ch2\u003eSlices are like references to arrays\u003c/h2\u003e\n \n \n \u003cp\u003e\n A slice does not store any data,\n\n\n it just describes a section of an underlying array.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Changing the elements of a slice modifies the\n\n\n corresponding elements of its underlying array.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Other slices that share the same underlying array will see those changes.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"slices-pointers.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tnames := [4]string{\n\t\t\"John\",\n\t\t\"Paul\",\n\t\t\"George\",\n\t\t\"Ringo\",\n\t}\n\tfmt.Println(names)\n\n\ta := names[0:2]\n\tb := names[1:3]\n\tfmt.Println(a, b)\n\n\tb[0] = \"XXX\"\n\tfmt.Println(a, b)\n\tfmt.Println(names)\n}\n","Hash":"RvHDudRqbwu/hRt7emjDaeWE4CI="}]},{"Title":"Slice literals","Content":"\n \u003ch2\u003eSlice literals\u003c/h2\u003e\n \n \n \u003cp\u003e\n A slice literal is like an array literal without the length.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This is an array literal:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003e[3]bool{true, true, false}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n And this creates the same array as above,\n\n\n then builds a slice that references it:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003e[]bool{true, true, false}\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"slice-literals.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tq := []int{2, 3, 5, 7, 11, 13}\n\tfmt.Println(q)\n\n\tr := []bool{true, false, true, true, false, true}\n\tfmt.Println(r)\n\n\ts := []struct {\n\t\ti int\n\t\tb bool\n\t}{\n\t\t{2, true},\n\t\t{3, false},\n\t\t{5, true},\n\t\t{7, true},\n\t\t{11, false},\n\t\t{13, true},\n\t}\n\tfmt.Println(s)\n}\n","Hash":"YuPRaUOZUWgeLJPhkSqy8UltIlU="}]},{"Title":"Slice defaults","Content":"\n \u003ch2\u003eSlice defaults\u003c/h2\u003e\n \n \n \u003cp\u003e\n When slicing, you may omit the high or low bounds to use their defaults instead.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The default is zero for the low bound and the length of the slice for the high bound.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n For the array\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar a [10]int\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n these slice expressions are equivalent:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ea[0:10]\na[:10]\na[0:]\na[:]\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"slice-bounds.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ts := []int{2, 3, 5, 7, 11, 13}\n\n\ts = s[1:4]\n\tfmt.Println(s)\n\n\ts = s[:2]\n\tfmt.Println(s)\n\n\ts = s[1:]\n\tfmt.Println(s)\n}\n","Hash":"126LTJWLpCX7iNszKYg/L7YEZxk="}]},{"Title":"Slice length and capacity","Content":"\n \u003ch2\u003eSlice length and capacity\u003c/h2\u003e\n \n \n \u003cp\u003e\n A slice has both a \u003ci\u003elength\u003c/i\u003e and a \u003ci\u003ecapacity\u003c/i\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The length of a slice is the number of elements it contains.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The capacity of a slice is the number of elements in the underlying array,\n\n\n counting from the first element in the slice.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The length and capacity of a slice \u003ccode\u003es\u003c/code\u003e can be obtained using the expressions\n\n\n \u003ccode\u003elen(s)\u003c/code\u003e and \u003ccode\u003ecap(s)\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can extend a slice\u0026#39;s length by re-slicing it,\n\n\n provided it has sufficient capacity.\n\n\n Try changing one of the slice operations in the example program to extend it\n\n\n beyond its capacity and see what happens.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"slice-len-cap.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ts := []int{2, 3, 5, 7, 11, 13}\n\tprintSlice(s)\n\n\t// Slice the slice to give it zero length.\n\ts = s[:0]\n\tprintSlice(s)\n\n\t// Extend its length.\n\ts = s[:4]\n\tprintSlice(s)\n\n\t// Drop its first two values.\n\ts = s[2:]\n\tprintSlice(s)\n}\n\nfunc printSlice(s []int) {\n\tfmt.Printf(\"len=%d cap=%d %v\\n\", len(s), cap(s), s)\n}\n","Hash":"kCcGGXYSE7FIvqMQhtNwpkn+kEY="}]},{"Title":"Nil slices","Content":"\n \u003ch2\u003eNil slices\u003c/h2\u003e\n \n \n \u003cp\u003e\n The zero value of a slice is \u003ccode\u003enil\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A nil slice has a length and capacity of 0\n\n\n and has no underlying array.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"nil-slices.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar s []int\n\tfmt.Println(s, len(s), cap(s))\n\tif s == nil {\n\t\tfmt.Println(\"nil!\")\n\t}\n}\n","Hash":"2gyXCfVBBtLAlqnLlLviWtSEVdA="}]},{"Title":"Creating a slice with make","Content":"\n \u003ch2\u003eCreating a slice with make\u003c/h2\u003e\n \n \n \u003cp\u003e\n Slices can be created with the built-in \u003ccode\u003emake\u003c/code\u003e function;\n\n\n this is how you create dynamically-sized arrays.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003emake\u003c/code\u003e function allocates a zeroed array\n\n\n and returns a slice that refers to that array:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ea := make([]int, 5) // len(a)=5\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n To specify a capacity, pass a third argument to \u003ccode\u003emake\u003c/code\u003e:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eb := make([]int, 0, 5) // len(b)=0, cap(b)=5\n\nb = b[:cap(b)] // len(b)=5, cap(b)=5\nb = b[1:] // len(b)=4, cap(b)=4\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"making-slices.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := make([]int, 5)\n\tprintSlice(\"a\", a)\n\n\tb := make([]int, 0, 5)\n\tprintSlice(\"b\", b)\n\n\tc := b[:2]\n\tprintSlice(\"c\", c)\n\n\td := c[2:5]\n\tprintSlice(\"d\", d)\n}\n\nfunc printSlice(s string, x []int) {\n\tfmt.Printf(\"%s len=%d cap=%d %v\\n\",\n\t\ts, len(x), cap(x), x)\n}\n","Hash":"/jN/up0H3+B/fuCVJtDq/ed1B8w="}]},{"Title":"Slices of slices","Content":"\n \u003ch2\u003eSlices of slices\u003c/h2\u003e\n \n \n \u003cp\u003e\n Slices can contain any type, including other slices.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"slices-of-slice.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\t// Create a tic-tac-toe board.\n\tboard := [][]string{\n\t\t[]string{\"_\", \"_\", \"_\"},\n\t\t[]string{\"_\", \"_\", \"_\"},\n\t\t[]string{\"_\", \"_\", \"_\"},\n\t}\n\n\t// The players take turns.\n\tboard[0][0] = \"X\"\n\tboard[2][2] = \"O\"\n\tboard[1][2] = \"X\"\n\tboard[1][0] = \"O\"\n\tboard[0][2] = \"X\"\n\n\tfor i := 0; i \u003c len(board); i++ {\n\t\tfmt.Printf(\"%s\\n\", strings.Join(board[i], \" \"))\n\t}\n}\n","Hash":"/8SscyOYcdD+cKUcGRMn+bu+z/s="}]},{"Title":"Appending to a slice","Content":"\n \u003ch2\u003eAppending to a slice\u003c/h2\u003e\n \n \n \u003cp\u003e\n It is common to append new elements to a slice, and so Go provides a built-in\n\n\n \u003ccode\u003eappend\u003c/code\u003e function. The \u003ca href=\"/pkg/builtin/#append\" target=\"_self\"\u003edocumentation\u003c/a\u003e\n\n\n of the built-in package describes \u003ccode\u003eappend\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003efunc append(s []T, vs ...T) []T\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n The first parameter \u003ccode\u003es\u003c/code\u003e of \u003ccode\u003eappend\u003c/code\u003e is a slice of type \u003ccode\u003eT\u003c/code\u003e, and the rest are\n\n\n \u003ccode\u003eT\u003c/code\u003e values to append to the slice.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The resulting value of \u003ccode\u003eappend\u003c/code\u003e is a slice containing all the elements of the\n\n\n original slice plus the provided values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n If the backing array of \u003ccode\u003es\u003c/code\u003e is too small to fit all the given values a bigger\n\n\n array will be allocated. The returned slice will point to the newly allocated\n\n\n array.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (To learn more about slices, read the \u003ca href=\"/blog/go-slices-usage-and-internals\" target=\"_self\"\u003eSlices: usage and internals\u003c/a\u003e article.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"append.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar s []int\n\tprintSlice(s)\n\n\t// append works on nil slices.\n\ts = append(s, 0)\n\tprintSlice(s)\n\n\t// The slice grows as needed.\n\ts = append(s, 1)\n\tprintSlice(s)\n\n\t// We can add more than one element at a time.\n\ts = append(s, 2, 3, 4)\n\tprintSlice(s)\n}\n\nfunc printSlice(s []int) {\n\tfmt.Printf(\"len=%d cap=%d %v\\n\", len(s), cap(s), s)\n}\n","Hash":"L+wfqhUrWgkLDxWCWN4wbYtQYjc="}]},{"Title":"Range","Content":"\n \u003ch2\u003eRange\u003c/h2\u003e\n \n \n \u003cp\u003e\n The \u003ccode\u003erange\u003c/code\u003e form of the \u003ccode\u003efor\u003c/code\u003e loop iterates over a slice or map.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n When ranging over a slice, two values are returned for each iteration.\n\n\n The first is the index, and the second is a copy of the element at that index.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"range.go","Content":"package main\n\nimport \"fmt\"\n\nvar pow = []int{1, 2, 4, 8, 16, 32, 64, 128}\n\nfunc main() {\n\tfor i, v := range pow {\n\t\tfmt.Printf(\"2**%d = %d\\n\", i, v)\n\t}\n}\n","Hash":"TrnpTuf792EXlQom9L3gMkUkz6U="}]},{"Title":"Range continued","Content":"\n \u003ch2\u003eRange continued\u003c/h2\u003e\n \n \n \u003cp\u003e\n You can skip the index or value by assigning to \u003ccode\u003e_\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003efor i, _ := range pow\nfor _, value := range pow\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n If you only want the index, you can omit the second variable.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003efor i := range pow\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"range-continued.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tpow := make([]int, 10)\n\tfor i := range pow {\n\t\tpow[i] = 1 \u003c\u003c uint(i) // == 2**i\n\t}\n\tfor _, value := range pow {\n\t\tfmt.Printf(\"%d\\n\", value)\n\t}\n}\n","Hash":"4B84qCi5dJR2qWuL6NhqWoy1TiY="}]},{"Title":"Exercise: Slices","Content":"\n \u003ch2\u003eExercise: Slices\u003c/h2\u003e\n \n \n \u003cp\u003e\n Implement \u003ccode\u003ePic\u003c/code\u003e. It should return a slice of length \u003ccode\u003edy\u003c/code\u003e, each element of which is a slice of \u003ccode\u003edx\u003c/code\u003e 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The choice of image is up to you. Interesting functions include \u003ccode\u003e(x+y)/2\u003c/code\u003e, \u003ccode\u003ex*y\u003c/code\u003e, and \u003ccode\u003ex^y\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (You need to use a loop to allocate each \u003ccode\u003e[]uint8\u003c/code\u003e inside the \u003ccode\u003e[][]uint8\u003c/code\u003e.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (Use \u003ccode\u003euint8(intValue)\u003c/code\u003e to convert between types.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-slices.go","Content":"package main\n\nimport \"golang.org/x/tour/pic\"\n\nfunc Pic(dx, dy int) [][]uint8 {\n}\n\nfunc main() {\n\tpic.Show(Pic)\n}\n","Hash":"kyr5jSqLKV1sQT6BThG9dVbEe8s="}]},{"Title":"Maps","Content":"\n \u003ch2\u003eMaps\u003c/h2\u003e\n \n \n \u003cp\u003e\n A map maps keys to values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The zero value of a map is \u003ccode\u003enil\u003c/code\u003e.\n\n\n A \u003ccode\u003enil\u003c/code\u003e map has no keys, nor can keys be added.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003emake\u003c/code\u003e function returns a map of the given type,\n\n\n initialized and ready for use.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"maps.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tLat, Long float64\n}\n\nvar m map[string]Vertex\n\nfunc main() {\n\tm = make(map[string]Vertex)\n\tm[\"Bell Labs\"] = Vertex{\n\t\t40.68433, -74.39967,\n\t}\n\tfmt.Println(m[\"Bell Labs\"])\n}\n","Hash":"rht5fv2C9kBGGZcCMrdHAdDZMWQ="}]},{"Title":"Map literals","Content":"\n \u003ch2\u003eMap literals\u003c/h2\u003e\n \n \n \u003cp\u003e\n Map literals are like struct literals, but the keys are required.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"map-literals.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tLat, Long float64\n}\n\nvar m = map[string]Vertex{\n\t\"Bell Labs\": Vertex{\n\t\t40.68433, -74.39967,\n\t},\n\t\"Google\": Vertex{\n\t\t37.42202, -122.08408,\n\t},\n}\n\nfunc main() {\n\tfmt.Println(m)\n}\n","Hash":"rWlZxNfgDt0zX5TH6PVvJJDyQnM="}]},{"Title":"Map literals continued","Content":"\n \u003ch2\u003eMap literals continued\u003c/h2\u003e\n \n \n \u003cp\u003e\n If the top-level type is just a type name, you can omit it from the elements of the literal.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"map-literals-continued.go","Content":"package main\n\nimport \"fmt\"\n\ntype Vertex struct {\n\tLat, Long float64\n}\n\nvar m = map[string]Vertex{\n\t\"Bell Labs\": {40.68433, -74.39967},\n\t\"Google\": {37.42202, -122.08408},\n}\n\nfunc main() {\n\tfmt.Println(m)\n}\n","Hash":"TfQqduBfdaXr+Lxb7DX9DaIMakg="}]},{"Title":"Mutating Maps","Content":"\n \u003ch2\u003eMutating Maps\u003c/h2\u003e\n \n \n \u003cp\u003e\n Insert or update an element in map \u003ccode\u003em\u003c/code\u003e:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003em[key] = elem\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Retrieve an element:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eelem = m[key]\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Delete an element:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003edelete(m, key)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Test that a key is present with a two-value assignment:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eelem, ok = m[key]\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n If \u003ccode\u003ekey\u003c/code\u003e is in \u003ccode\u003em\u003c/code\u003e, \u003ccode\u003eok\u003c/code\u003e is \u003ccode\u003etrue\u003c/code\u003e. If not, \u003ccode\u003eok\u003c/code\u003e is \u003ccode\u003efalse\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n If \u003ccode\u003ekey\u003c/code\u003e is not in the map, then \u003ccode\u003eelem\u003c/code\u003e is the zero value for the map\u0026#39;s element type.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eNote:\u003c/b\u003e If \u003ccode\u003eelem\u003c/code\u003e or \u003ccode\u003eok\u003c/code\u003e have not yet been declared you could use a short declaration form:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eelem, ok := m[key]\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"mutating-maps.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tm := make(map[string]int)\n\n\tm[\"Answer\"] = 42\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\n\tm[\"Answer\"] = 48\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\n\tdelete(m, \"Answer\")\n\tfmt.Println(\"The value:\", m[\"Answer\"])\n\n\tv, ok := m[\"Answer\"]\n\tfmt.Println(\"The value:\", v, \"Present?\", ok)\n}\n","Hash":"Yb5V377DiiLAd8aCfxxtC0S/sdc="}]},{"Title":"Exercise: Maps","Content":"\n \u003ch2\u003eExercise: Maps\u003c/h2\u003e\n \n \n \u003cp\u003e\n Implement \u003ccode\u003eWordCount\u003c/code\u003e. It should return a map of the counts of each “word” in the string \u003ccode\u003es\u003c/code\u003e. The \u003ccode\u003ewc.Test\u003c/code\u003e function runs a test suite against the provided function and prints success or failure.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You might find \u003ca href=\"/pkg/strings/#Fields\" target=\"_self\"\u003estrings.Fields\u003c/a\u003e helpful.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-maps.go","Content":"package main\n\nimport (\n\t\"golang.org/x/tour/wc\"\n)\n\nfunc WordCount(s string) map[string]int {\n\treturn map[string]int{\"x\": 1}\n}\n\nfunc main() {\n\twc.Test(WordCount)\n}\n","Hash":"412+IoCx6S2as89oIhOsgqFJUUM="}]},{"Title":"Function values","Content":"\n \u003ch2\u003eFunction values\u003c/h2\u003e\n \n \n \u003cp\u003e\n Functions are values too. They can be passed around just like other values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Function values may be used as function arguments and return values.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"function-values.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc compute(fn func(float64, float64) float64) float64 {\n\treturn fn(3, 4)\n}\n\nfunc main() {\n\thypot := func(x, y float64) float64 {\n\t\treturn math.Sqrt(x*x + y*y)\n\t}\n\tfmt.Println(hypot(5, 12))\n\n\tfmt.Println(compute(hypot))\n\tfmt.Println(compute(math.Pow))\n}\n","Hash":"/ZOMEENCqbM+TbJAYLHcNv60gfY="}]},{"Title":"Function closures","Content":"\n \u003ch2\u003eFunction closures\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is \u0026#34;bound\u0026#34; to the variables.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n For example, the \u003ccode\u003eadder\u003c/code\u003e function returns a closure. Each closure is bound to its own \u003ccode\u003esum\u003c/code\u003e variable.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"function-closures.go","Content":"package main\n\nimport \"fmt\"\n\nfunc adder() func(int) int {\n\tsum := 0\n\treturn func(x int) int {\n\t\tsum += x\n\t\treturn sum\n\t}\n}\n\nfunc main() {\n\tpos, neg := adder(), adder()\n\tfor i := 0; i \u003c 10; i++ {\n\t\tfmt.Println(\n\t\t\tpos(i),\n\t\t\tneg(-2*i),\n\t\t)\n\t}\n}\n","Hash":"XQlACZHW1Wkhc0nZnpZGvrVgkWo="}]},{"Title":"Exercise: Fibonacci closure","Content":"\n \u003ch2\u003eExercise: Fibonacci closure\u003c/h2\u003e\n \n \n \u003cp\u003e\n Let\u0026#39;s have some fun with functions.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Implement a \u003ccode\u003efibonacci\u003c/code\u003e function that returns a function (a closure) that\n\n\n returns successive \u003ca href=\"https://en.wikipedia.org/wiki/Fibonacci_number\" target=\"_blank\"\u003efibonacci numbers\u003c/a\u003e\n\n\n (0, 1, 1, 2, 3, 5, ...).\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-fibonacci-closure.go","Content":"package main\n\nimport \"fmt\"\n\n// fibonacci is a function that returns\n// a function that returns an int.\nfunc fibonacci() func() int {\n}\n\nfunc main() {\n\tf := fibonacci()\n\tfor i := 0; i \u003c 10; i++ {\n\t\tfmt.Println(f())\n\t}\n}\n","Hash":"BQXS8AUg/LPWf2asWqi6FZl1+aU="}]},{"Title":"Congratulations!","Content":"\n \u003ch2\u003eCongratulations!\u003c/h2\u003e\n \n \n \u003cp\u003e\n You finished this lesson!\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can go back to the list of \u003ca href=\"/tour/list\" target=\"_self\"\u003emodules\u003c/a\u003e to find what to learn next, or continue with the \u003ca href=\"javascript:click(\u0026#39;.next-page\u0026#39;)\" target=\"_self\"\u003enext lesson\u003c/a\u003e.\n \u003c/p\u003e\n \n\n","Files":[]}]} ,"welcome":{"Title":"Welcome!","Description":"Learn how to use this tour: including how to navigate the different lessons and how to run code.","Pages":[{"Title":"Hello, 世界","Content":"\n \u003ch2\u003eHello, 世界\u003c/h2\u003e\n \n \n \u003cp\u003e\n Welcome to a tour of the \u003ca href=\"/\" target=\"_self\"\u003eGo programming language\u003c/a\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The tour is divided into a list of modules that you can\n\n\n access by clicking on\n\n\n \u003ca href=\"javascript:highlight(\u0026#34;.logo\u0026#34;)\" target=\"_self\"\u003eA Tour of Go\u003c/a\u003e on the top left of the page.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can also view the table of contents at any time by clicking on the \u003ca href=\"javascript:highlightAndClick(\u0026#34;.nav\u0026#34;)\" target=\"_self\"\u003emenu\u003c/a\u003e on the top right of the page.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Throughout the tour you will find a series of slides and exercises for you\n\n\n to complete.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can navigate through them using\n \u003c/p\u003e\n \n\n \u003cul\u003e\n \n \u003cli\u003e\u003ca href=\"javascript:highlight(\u0026#34;.prev-page\u0026#34;)\" target=\"_self\"\u003e\u0026#34;previous\u0026#34;\u003c/a\u003e or \u003ccode\u003ePageUp\u003c/code\u003e to go to the previous page,\u003c/li\u003e\n \n \u003c/ul\u003e\n\n \u003cul\u003e\n \n \u003cli\u003e\u003ca href=\"javascript:highlight(\u0026#34;.next-page\u0026#34;)\" target=\"_self\"\u003e\u0026#34;next\u0026#34;\u003c/a\u003e or \u003ccode\u003ePageDown\u003c/code\u003e to go to the next page.\u003c/li\u003e\n \n \u003c/ul\u003e\n\n \n \u003cp\u003e\n The tour is interactive. Click the\n\n\n \u003ca href=\"javascript:highlightAndClick(\u0026#34;#run\u0026#34;)\" target=\"_self\"\u003eRun\u003c/a\u003e button now\n\n\n (or press \u003ccode\u003eShift\u003c/code\u003e + \u003ccode\u003eEnter\u003c/code\u003e) to compile and run the program on\n\n\n a remote server.\n\n\n The result is displayed below the code.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n These example programs demonstrate different aspects of Go. The programs in the tour are meant to be starting points for your own experimentation.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Edit the program and run it again.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n When you click on \u003ca href=\"javascript:highlightAndClick(\u0026#34;#format\u0026#34;)\" target=\"_self\"\u003eFormat\u003c/a\u003e\n\n\n (shortcut: \u003ccode\u003eCtrl\u003c/code\u003e + \u003ccode\u003eEnter\u003c/code\u003e), the text in the editor is formatted using the\n\n\n \u003ca href=\"/cmd/gofmt/\" target=\"_self\"\u003egofmt\u003c/a\u003e tool. You can switch syntax highlighting on and off\n\n\n by clicking on the \u003ca href=\"javascript:highlightAndClick(\u0026#34;.syntax-checkbox\u0026#34;)\" target=\"_self\"\u003esyntax\u003c/a\u003e button.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n When you\u0026#39;re ready to move on, click the \u003ca href=\"javascript:highlightAndClick(\u0026#34;.next-page\u0026#34;)\" target=\"_self\"\u003eright arrow\u003c/a\u003e below or type the \u003ccode\u003ePageDown\u003c/code\u003e key.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"hello.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello, 世界\")\n}\n","Hash":"DwfZCJ2NK3FTIJnSUkZkwzma41c="}]},{"Title":"Go local","Content":"\n \u003ch2\u003eGo local\u003c/h2\u003e\n \n \n \u003cp\u003e\n The tour is available in other languages:\n \u003c/p\u003e\n \n\n \u003cul\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-br.appspot.com/\" target=\"_blank\"\u003eBrazilian Portuguese — Português do Brasil\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-ca.appspot.com/\" target=\"_blank\"\u003eCatalan — Català\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://tour.go-zh.org/\" target=\"_blank\"\u003eSimplified Chinese — 中文(简体)\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-cz.appspot.com/\" target=\"_blank\"\u003eCzech — Česky\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-id2.appspot.com/\" target=\"_blank\"\u003eIndonesian — Bahasa Indonesia\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-jp.appspot.com/\" target=\"_blank\"\u003eJapanese — 日本語\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-ko.appspot.com/\" target=\"_blank\"\u003eKorean — 한국어\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-pl1.appspot.com/\" target=\"_blank\"\u003ePolish — Polski\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-th.appspot.com/\" target=\"_blank\"\u003eThai — ภาษาไทย\u003c/a\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ca href=\"https://go-tour-ua-translation.lm.r.appspot.com/\" target=\"_blank\"\u003eUkrainian — Українською\u003c/a\u003e\u003c/li\u003e\n \n \u003c/ul\u003e\n\n \n \u003cp\u003e\n Click the \u003ca href=\"javascript:highlightAndClick(\u0026#34;.next-page\u0026#34;)\" target=\"_self\"\u003e\u0026#34;next\u0026#34;\u003c/a\u003e button or type \u003ccode\u003ePageDown\u003c/code\u003e to continue.\n \u003c/p\u003e\n \n\n","Files":[]},{"Title":"Go offline (optional)","Content":"\n \u003ch2\u003eGo offline (optional)\u003c/h2\u003e\n \n \n \u003cp\u003e\n This tour is also available as a stand-alone program that you can use\n\n\n without access to the internet. It builds and runs the code samples on\n\n\n your own machine.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To run the tour locally, you\u0026#39;ll need to first\n\n\n \u003ca href=\"/doc/install\" target=\"_self\"\u003einstall Go\u003c/a\u003e and then run:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ego install golang.org/x/website/tour@latest\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n This will place a \u003ccode\u003etour\u003c/code\u003e binary in your\n\n\n \u003ca href=\"/cmd/go/#hdr-GOPATH_and_Modules\" target=\"_self\"\u003eGOPATH\u003c/a\u003e\u0026#39;s \u003ccode\u003ebin\u003c/code\u003e directory.\n\n\n When you run the tour program, it will open a web browser displaying\n\n\n your local version of the tour.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Of course, you can continue to take the tour through this web site.\n \u003c/p\u003e\n \n\n","Files":[]},{"Title":"The Go Playground","Content":"\n \u003ch2\u003eThe Go Playground\u003c/h2\u003e\n \n \n \u003cp\u003e\n This tour is built atop the \u003ca href=\"https://play.golang.org/\" target=\"_blank\"\u003eGo Playground\u003c/a\u003e, a\n\n\n web service that runs on \u003ca href=\"/\" target=\"_self\"\u003egolang.org\u003c/a\u003e\u0026#39;s servers.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The service receives a Go program, compiles, links, and runs the program inside\n\n\n a sandbox, then returns the output.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n There are limitations to the programs that can be run in the playground:\n \u003c/p\u003e\n \n\n \u003cul\u003e\n \n \u003cli\u003eIn the playground the time begins at 2009-11-10 23:00:00 UTC (determining the significance of this date is an exercise for the reader). This makes it easier to cache programs by giving them deterministic output.\u003c/li\u003e\n \n \u003c/ul\u003e\n\n \u003cul\u003e\n \n \u003cli\u003eThere are also limits on execution time and on CPU and memory usage, and the program cannot access external network hosts.\u003c/li\u003e\n \n \u003c/ul\u003e\n\n \n \u003cp\u003e\n The playground uses the latest stable release of Go.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Read \u0026#34;\u003ca href=\"/blog/playground\" target=\"_self\"\u003eInside the Go Playground\u003c/a\u003e\u0026#34; to learn more.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"sandbox.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tfmt.Println(\"Welcome to the playground!\")\n\n\tfmt.Println(\"The time is\", time.Now())\n}\n","Hash":"bOpKtZ8cTKG+qhINnOZDcJhhNQc="}]},{"Title":"Congratulations","Content":"\n \u003ch2\u003eCongratulations\u003c/h2\u003e\n \n \n \u003cp\u003e\n You\u0026#39;ve finished the first module of the tour!\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Now click on \u003ca href=\"javascript:highlightAndClick(\u0026#34;.logo\u0026#34;)\" target=\"_self\"\u003eA Tour of Go\u003c/a\u003e to find out what else\n\n\n you can learn about Go, or go directly to the \u003ca href=\"javascript:click(\u0026#39;.next-page\u0026#39;)\" target=\"_self\"\u003enext lesson\u003c/a\u003e.\n \u003c/p\u003e\n \n\n","Files":[]}]} ,"basics":{"Title":"Packages, variables, and functions.","Description":"Learn the basic components of any Go program.","Pages":[{"Title":"Packages","Content":"\n \u003ch2\u003ePackages\u003c/h2\u003e\n \n \n \u003cp\u003e\n Every Go program is made up of packages.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Programs start running in package \u003ccode\u003emain\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This program is using the packages with import paths \u003ccode\u003e\u0026#34;fmt\u0026#34;\u003c/code\u003e and \u003ccode\u003e\u0026#34;math/rand\u0026#34;\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n By convention, the package name is the same as the last element of the import path. For instance, the \u003ccode\u003e\u0026#34;math/rand\u0026#34;\u003c/code\u003e package comprises files that begin with the statement \u003ccode\u003epackage rand\u003c/code\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"packages.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n)\n\nfunc main() {\n\tfmt.Println(\"My favorite number is\", rand.Intn(10))\n}\n","Hash":"3pUhjlSXGcPdkYyhESbolPagQdc="}]},{"Title":"Imports","Content":"\n \u003ch2\u003eImports\u003c/h2\u003e\n \n \n \u003cp\u003e\n This code groups the imports into a parenthesized, \u0026#34;factored\u0026#34; import statement.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can also write multiple import statements, like:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eimport \u0026#34;fmt\u0026#34;\nimport \u0026#34;math\u0026#34;\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n But it is good style to use the factored import statement.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"imports.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc main() {\n\tfmt.Printf(\"Now you have %g problems.\\n\", math.Sqrt(7))\n}\n","Hash":"lPR2lIWDxWwgjpowRHDjGX2RrHo="}]},{"Title":"Exported names","Content":"\n \u003ch2\u003eExported names\u003c/h2\u003e\n \n \n \u003cp\u003e\n In Go, a name is exported if it begins with a capital letter.\n\n\n For example, \u003ccode\u003ePizza\u003c/code\u003e is an exported name, as is \u003ccode\u003ePi\u003c/code\u003e, which is exported from\n\n\n the \u003ccode\u003emath\u003c/code\u003e package.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003epizza\u003c/code\u003e and \u003ccode\u003epi\u003c/code\u003e do not start with a capital letter, so they are not exported.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n When importing a package, you can refer only to its exported names.\n\n\n Any \u0026#34;unexported\u0026#34; names are not accessible from outside the package.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Run the code. Notice the error message.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To fix the error, rename \u003ccode\u003emath.pi\u003c/code\u003e to \u003ccode\u003emath.Pi\u003c/code\u003e and try it again.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exported-names.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc main() {\n\tfmt.Println(math.pi)\n}\n","Hash":"8BpBAuTlXDhXXWKPhaWnx31jlc4="}]},{"Title":"Functions","Content":"\n \u003ch2\u003eFunctions\u003c/h2\u003e\n \n \n \u003cp\u003e\n A function can take zero or more arguments.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n In this example, \u003ccode\u003eadd\u003c/code\u003e takes two parameters of type \u003ccode\u003eint\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Notice that the type comes \u003ci\u003eafter\u003c/i\u003e the variable name.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (For more about why types look the way they do, see the \u003ca href=\"/blog/gos-declaration-syntax\" target=\"_self\"\u003earticle on Go\u0026#39;s declaration syntax\u003c/a\u003e.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"functions.go","Content":"package main\n\nimport \"fmt\"\n\nfunc add(x int, y int) int {\n\treturn x + y\n}\n\nfunc main() {\n\tfmt.Println(add(42, 13))\n}\n","Hash":"QaLixiSTN/1jtTTP0xgV88EiWbc="}]},{"Title":"Functions continued","Content":"\n \u003ch2\u003eFunctions continued\u003c/h2\u003e\n \n \n \u003cp\u003e\n When two or more consecutive named function parameters share a type, you can omit the type from all but the last.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n In this example, we shortened\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ex int, y int\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n to\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ex, y int\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"functions-continued.go","Content":"package main\n\nimport \"fmt\"\n\nfunc add(x, y int) int {\n\treturn x + y\n}\n\nfunc main() {\n\tfmt.Println(add(42, 13))\n}\n","Hash":"qq29LGsGzc3ACpeMJkDSISHbqoM="}]},{"Title":"Multiple results","Content":"\n \u003ch2\u003eMultiple results\u003c/h2\u003e\n \n \n \u003cp\u003e\n A function can return any number of results.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003eswap\u003c/code\u003e function returns two strings.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"multiple-results.go","Content":"package main\n\nimport \"fmt\"\n\nfunc swap(x, y string) (string, string) {\n\treturn y, x\n}\n\nfunc main() {\n\ta, b := swap(\"hello\", \"world\")\n\tfmt.Println(a, b)\n}\n","Hash":"VjRC6BmdaRQPFvF3JIg+6vzY0rc="}]},{"Title":"Named return values","Content":"\n \u003ch2\u003eNamed return values\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go\u0026#39;s return values may be named. If so, they are treated as variables defined at the top of the function.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n These names should be used to document the meaning of the return values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A \u003ccode\u003ereturn\u003c/code\u003e statement without arguments returns the named return values. This is known as a \u0026#34;naked\u0026#34; return.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"named-results.go","Content":"package main\n\nimport \"fmt\"\n\nfunc split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}\n\nfunc main() {\n\tfmt.Println(split(17))\n}\n","Hash":"AX7YGFmJ2woSa5QTgkprkNt7Ezo="}]},{"Title":"Variables","Content":"\n \u003ch2\u003eVariables\u003c/h2\u003e\n \n \n \u003cp\u003e\n The \u003ccode\u003evar\u003c/code\u003e statement declares a list of variables; as in function argument lists, the type is last.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A \u003ccode\u003evar\u003c/code\u003e statement can be at package or function level. We see both in this example.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"variables.go","Content":"package main\n\nimport \"fmt\"\n\nvar c, python, java bool\n\nfunc main() {\n\tvar i int\n\tfmt.Println(i, c, python, java)\n}\n","Hash":"IA/svTzSJDH25Jj1VK/auHbrfx0="}]},{"Title":"Variables with initializers","Content":"\n \u003ch2\u003eVariables with initializers\u003c/h2\u003e\n \n \n \u003cp\u003e\n A var declaration can include initializers, one per variable.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n If an initializer is present, the type can be omitted; the variable will take the type of the initializer.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"variables-with-initializers.go","Content":"package main\n\nimport \"fmt\"\n\nvar i, j int = 1, 2\n\nfunc main() {\n\tvar c, python, java = true, false, \"no!\"\n\tfmt.Println(i, j, c, python, java)\n}\n","Hash":"kxySFjAqlylR+dCDsQvw5Ni0k8Q="}]},{"Title":"Short variable declarations","Content":"\n \u003ch2\u003eShort variable declarations\u003c/h2\u003e\n \n \n \u003cp\u003e\n Inside a function, the \u003ccode\u003e:=\u003c/code\u003e short assignment statement can be used in place of a \u003ccode\u003evar\u003c/code\u003e declaration with implicit type.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Outside a function, every statement begins with a keyword (\u003ccode\u003evar\u003c/code\u003e, \u003ccode\u003efunc\u003c/code\u003e, and so on) and so the \u003ccode\u003e:=\u003c/code\u003e construct is not available.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"short-variable-declarations.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar i, j int = 1, 2\n\tk := 3\n\tc, python, java := true, false, \"no!\"\n\n\tfmt.Println(i, j, k, c, python, java)\n}\n","Hash":"Zz6rkZD1xvZ8Y0U9xTSOJQ3Ec3o="}]},{"Title":"Basic types","Content":"\n \u003ch2\u003eBasic types\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go\u0026#39;s basic types are\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ebool\n\nstring\n\nint int8 int16 int32 int64\nuint uint8 uint16 uint32 uint64 uintptr\n\nbyte // alias for uint8\n\nrune // alias for int32\n // represents a Unicode code point\n\nfloat32 float64\n\ncomplex64 complex128\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n The example shows variables of several types,\n\n\n and also that variable declarations may be \u0026#34;factored\u0026#34; into blocks,\n\n\n as with import statements.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ccode\u003eint\u003c/code\u003e, \u003ccode\u003euint\u003c/code\u003e, and \u003ccode\u003euintptr\u003c/code\u003e types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.\n\n\n When you need an integer value you should use \u003ccode\u003eint\u003c/code\u003e unless you have a specific reason to use a sized or unsigned integer type.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"basic-types.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math/cmplx\"\n)\n\nvar (\n\tToBe bool = false\n\tMaxInt uint64 = 1\u003c\u003c64 - 1\n\tz complex128 = cmplx.Sqrt(-5 + 12i)\n)\n\nfunc main() {\n\tfmt.Printf(\"Type: %T Value: %v\\n\", ToBe, ToBe)\n\tfmt.Printf(\"Type: %T Value: %v\\n\", MaxInt, MaxInt)\n\tfmt.Printf(\"Type: %T Value: %v\\n\", z, z)\n}\n","Hash":"uwd31YbyEsiXFNRjmD+EEctimpc="}]},{"Title":"Zero values","Content":"\n \u003ch2\u003eZero values\u003c/h2\u003e\n \n \n \u003cp\u003e\n Variables declared without an explicit initial value are given their\n\n\n \u003ci\u003ezero value\u003c/i\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The zero value is:\n \u003c/p\u003e\n \n\n \u003cul\u003e\n \n \u003cli\u003e\u003ccode\u003e0\u003c/code\u003e for numeric types,\u003c/li\u003e\n \n \u003cli\u003e\u003ccode\u003efalse\u003c/code\u003e for the boolean type, and\u003c/li\u003e\n \n \u003cli\u003e\u003ccode\u003e\u0026#34;\u0026#34;\u003c/code\u003e (the empty string) for strings.\u003c/li\u003e\n \n \u003c/ul\u003e\n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"zero.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar i int\n\tvar f float64\n\tvar b bool\n\tvar s string\n\tfmt.Printf(\"%v %v %v %q\\n\", i, f, b, s)\n}\n","Hash":"3oy0IiXxtycOjQCkuWLqLa29xzU="}]},{"Title":"Type conversions","Content":"\n \u003ch2\u003eType conversions\u003c/h2\u003e\n \n \n \u003cp\u003e\n The expression \u003ccode\u003eT(v)\u003c/code\u003e converts the value \u003ccode\u003ev\u003c/code\u003e to the type \u003ccode\u003eT\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Some numeric conversions:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar i int = 42\nvar f float64 = float64(i)\nvar u uint = uint(f)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Or, put more simply:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ei := 42\nf := float64(i)\nu := uint(f)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Unlike in C, in Go assignment between items of different type requires an\n\n\n explicit conversion.\n\n\n Try removing the \u003ccode\u003efloat64\u003c/code\u003e or \u003ccode\u003euint\u003c/code\u003e conversions in the example and see what happens.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"type-conversions.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc main() {\n\tvar x, y int = 3, 4\n\tvar f float64 = math.Sqrt(float64(x*x + y*y))\n\tvar z uint = uint(f)\n\tfmt.Println(x, y, z)\n}\n","Hash":"JGbg9tutd+lDvoRTFMaTExwsKAk="}]},{"Title":"Type inference","Content":"\n \u003ch2\u003eType inference\u003c/h2\u003e\n \n \n \u003cp\u003e\n When declaring a variable without specifying an explicit type (either by using the \u003ccode\u003e:=\u003c/code\u003e syntax or \u003ccode\u003evar =\u003c/code\u003e expression syntax), the variable\u0026#39;s type is inferred from the value on the right hand side.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n When the right hand side of the declaration is typed, the new variable is of that same type:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003evar i int\nj := i // j is an int\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n But when the right hand side contains an untyped numeric constant, the new variable may be an \u003ccode\u003eint\u003c/code\u003e, \u003ccode\u003efloat64\u003c/code\u003e, or \u003ccode\u003ecomplex128\u003c/code\u003e depending on the precision of the constant:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ei := 42 // int\nf := 3.142 // float64\ng := 0.867 \u0026#43; 0.5i // complex128\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Try changing the initial value of \u003ccode\u003ev\u003c/code\u003e in the example code and observe how its type is affected.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"type-inference.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tv := 42 // change me!\n\tfmt.Printf(\"v is of type %T\\n\", v)\n}\n","Hash":"1K7bgjkrtR5wRA38ePeFIDpEEbY="}]},{"Title":"Constants","Content":"\n \u003ch2\u003eConstants\u003c/h2\u003e\n \n \n \u003cp\u003e\n Constants are declared like variables, but with the \u003ccode\u003econst\u003c/code\u003e keyword.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Constants can be character, string, boolean, or numeric values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Constants cannot be declared using the \u003ccode\u003e:=\u003c/code\u003e syntax.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"constants.go","Content":"package main\n\nimport \"fmt\"\n\nconst Pi = 3.14\n\nfunc main() {\n\tconst World = \"世界\"\n\tfmt.Println(\"Hello\", World)\n\tfmt.Println(\"Happy\", Pi, \"Day\")\n\n\tconst Truth = true\n\tfmt.Println(\"Go rules?\", Truth)\n}\n","Hash":"/KqzBNsqfHiVdOg92MiKtXMexkU="}]},{"Title":"Numeric Constants","Content":"\n \u003ch2\u003eNumeric Constants\u003c/h2\u003e\n \n \n \u003cp\u003e\n Numeric constants are high-precision \u003ci\u003evalues\u003c/i\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n An untyped constant takes the type needed by its context.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Try printing \u003ccode\u003eneedInt(Big)\u003c/code\u003e too.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (An \u003ccode\u003eint\u003c/code\u003e can store at maximum a 64-bit integer, and sometimes less.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"numeric-constants.go","Content":"package main\n\nimport \"fmt\"\n\nconst (\n\t// Create a huge number by shifting a 1 bit left 100 places.\n\t// In other words, the binary number that is 1 followed by 100 zeroes.\n\tBig = 1 \u003c\u003c 100\n\t// Shift it right again 99 places, so we end up with 1\u003c\u003c1, or 2.\n\tSmall = Big \u003e\u003e 99\n)\n\nfunc needInt(x int) int { return x*10 + 1 }\nfunc needFloat(x float64) float64 {\n\treturn x * 0.1\n}\n\nfunc main() {\n\tfmt.Println(needInt(Small))\n\tfmt.Println(needFloat(Small))\n\tfmt.Println(needFloat(Big))\n}\n","Hash":"mpa1CTTD2KsjpKwVpbHo9Jz/ujM="}]},{"Title":"Congratulations!","Content":"\n \u003ch2\u003eCongratulations!\u003c/h2\u003e\n \n \n \u003cp\u003e\n You finished this lesson!\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can go back to the list of \u003ca href=\"/tour/list\" target=\"_self\"\u003emodules\u003c/a\u003e to find what to learn next, or continue with the \u003ca href=\"javascript:click(\u0026#39;.next-page\u0026#39;)\" target=\"_self\"\u003enext lesson\u003c/a\u003e.\n \u003c/p\u003e\n \n\n","Files":[]}]} ,"concurrency":{"Title":"Concurrency","Description":"Go provides concurrency constructions as part of the core language. This lesson presents them and gives some examples on how they can be used.","Pages":[{"Title":"Goroutines","Content":"\n \u003ch2\u003eGoroutines\u003c/h2\u003e\n \n \n \u003cp\u003e\n A \u003ci\u003egoroutine\u003c/i\u003e is a lightweight thread managed by the Go runtime.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ego f(x, y, z)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n starts a new goroutine running\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ef(x, y, z)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n The evaluation of \u003ccode\u003ef\u003c/code\u003e, \u003ccode\u003ex\u003c/code\u003e, \u003ccode\u003ey\u003c/code\u003e, and \u003ccode\u003ez\u003c/code\u003e happens in the current goroutine and the execution of \u003ccode\u003ef\u003c/code\u003e happens in the new goroutine.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Goroutines run in the same address space, so access to shared memory must be synchronized. The \u003ca href=\"/pkg/sync/\" target=\"_self\"\u003e\u003ccode\u003esync\u003c/code\u003e\u003c/a\u003e package provides useful primitives, although you won\u0026#39;t need them much in Go as there are other primitives. (See the next slide.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"goroutines.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc say(s string) {\n\tfor i := 0; i \u003c 5; i++ {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfmt.Println(s)\n\t}\n}\n\nfunc main() {\n\tgo say(\"world\")\n\tsay(\"hello\")\n}\n","Hash":"V0QWmtbyKtRACHLggPFEhVfjtHk="}]},{"Title":"Channels","Content":"\n \u003ch2\u003eChannels\u003c/h2\u003e\n \n \n \u003cp\u003e\n Channels are a typed conduit through which you can send and receive values with the channel operator, \u003ccode\u003e\u0026lt;-\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ech \u0026lt;- v // Send v to channel ch.\nv := \u0026lt;-ch // Receive from ch, and\n // assign value to v.\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n (The data flows in the direction of the arrow.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Like maps and slices, channels must be created before use:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ech := make(chan int)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The example code sums the numbers in a slice, distributing the work between two goroutines.\n\n\n Once both goroutines have completed their computation, it calculates the final result.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"channels.go","Content":"package main\n\nimport \"fmt\"\n\nfunc sum(s []int, c chan int) {\n\tsum := 0\n\tfor _, v := range s {\n\t\tsum += v\n\t}\n\tc \u003c- sum // send sum to c\n}\n\nfunc main() {\n\ts := []int{7, 2, 8, -9, 4, 0}\n\n\tc := make(chan int)\n\tgo sum(s[:len(s)/2], c)\n\tgo sum(s[len(s)/2:], c)\n\tx, y := \u003c-c, \u003c-c // receive from c\n\n\tfmt.Println(x, y, x+y)\n}\n","Hash":"yAHQ/AWnRNOA7NerKhJ0sXl7Q20="}]},{"Title":"Buffered Channels","Content":"\n \u003ch2\u003eBuffered Channels\u003c/h2\u003e\n \n \n \u003cp\u003e\n Channels can be \u003ci\u003ebuffered\u003c/i\u003e. Provide the buffer length as the second argument to \u003ccode\u003emake\u003c/code\u003e to initialize a buffered channel:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ech := make(chan int, 100)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Modify the example to overfill the buffer and see what happens.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"buffered-channels.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tch := make(chan int, 2)\n\tch \u003c- 1\n\tch \u003c- 2\n\tfmt.Println(\u003c-ch)\n\tfmt.Println(\u003c-ch)\n}\n","Hash":"HNpu4gbNWpP4WP/6znFerbBix/U="}]},{"Title":"Range and Close","Content":"\n \u003ch2\u003eRange and Close\u003c/h2\u003e\n \n \n \u003cp\u003e\n A sender can \u003ccode\u003eclose\u003c/code\u003e a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ev, ok := \u0026lt;-ch\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003eok\u003c/code\u003e is \u003ccode\u003efalse\u003c/code\u003e if there are no more values to receive and the channel is closed.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The loop \u003ccode\u003efor i := range c\u003c/code\u003e receives values from the channel repeatedly until it is closed.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eNote:\u003c/b\u003e Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eAnother note:\u003c/b\u003e Channels aren\u0026#39;t like files; you don\u0026#39;t usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a \u003ccode\u003erange\u003c/code\u003e loop.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"range-and-close.go","Content":"package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc fibonacci(n int, c chan int) {\n\tx, y := 0, 1\n\tfor i := 0; i \u003c n; i++ {\n\t\tc \u003c- x\n\t\tx, y = y, x+y\n\t}\n\tclose(c)\n}\n\nfunc main() {\n\tc := make(chan int, 10)\n\tgo fibonacci(cap(c), c)\n\tfor i := range c {\n\t\tfmt.Println(i)\n\t}\n}\n","Hash":"4FtqldYWvLh1vO6HNWvr/RcwgBk="}]},{"Title":"Select","Content":"\n \u003ch2\u003eSelect\u003c/h2\u003e\n \n \n \u003cp\u003e\n The \u003ccode\u003eselect\u003c/code\u003e statement lets a goroutine wait on multiple communication operations.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n A \u003ccode\u003eselect\u003c/code\u003e blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"select.go","Content":"package main\n\nimport \"fmt\"\n\nfunc fibonacci(c, quit chan int) {\n\tx, y := 0, 1\n\tfor {\n\t\tselect {\n\t\tcase c \u003c- x:\n\t\t\tx, y = y, x+y\n\t\tcase \u003c-quit:\n\t\t\tfmt.Println(\"quit\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc main() {\n\tc := make(chan int)\n\tquit := make(chan int)\n\tgo func() {\n\t\tfor i := 0; i \u003c 10; i++ {\n\t\t\tfmt.Println(\u003c-c)\n\t\t}\n\t\tquit \u003c- 0\n\t}()\n\tfibonacci(c, quit)\n}\n","Hash":"fsgO6l9yS4Jib1uMTvh+1giFpfg="}]},{"Title":"Default Selection","Content":"\n \u003ch2\u003eDefault Selection\u003c/h2\u003e\n \n \n \u003cp\u003e\n The \u003ccode\u003edefault\u003c/code\u003e case in a \u003ccode\u003eselect\u003c/code\u003e is run if no other case is ready.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Use a \u003ccode\u003edefault\u003c/code\u003e case to try a send or receive without blocking:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eselect {\ncase i := \u0026lt;-c:\n // use i\ndefault:\n // receiving from c would block\n}\u003c/pre\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"default-selection.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\ttick := time.Tick(100 * time.Millisecond)\n\tboom := time.After(500 * time.Millisecond)\n\tfor {\n\t\tselect {\n\t\tcase \u003c-tick:\n\t\t\tfmt.Println(\"tick.\")\n\t\tcase \u003c-boom:\n\t\t\tfmt.Println(\"BOOM!\")\n\t\t\treturn\n\t\tdefault:\n\t\t\tfmt.Println(\" .\")\n\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t}\n\t}\n}\n","Hash":"13nYcML2cEMSMR4KdD858o88aTY="}]},{"Title":"Exercise: Equivalent Binary Trees","Content":"\n \u003ch2\u003eExercise: Equivalent Binary Trees\u003c/h2\u003e\n \n \n \u003cp\u003e\n There can be many different binary trees with the same sequence of values stored in it. For example, here are two binary trees storing the sequence 1, 1, 2, 3, 5, 8, 13.\n \u003c/p\u003e\n \n\n \u003cimg src=\"/tour/static/img/tree.png\"\u003e\n\n \n \u003cp\u003e\n A function to check whether two binary trees store the same sequence is quite complex in most languages. We\u0026#39;ll use Go\u0026#39;s concurrency and channels to write a simple solution.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This example uses the \u003ccode\u003etree\u003c/code\u003e package, which defines the type:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003etype Tree struct {\n Left *Tree\n Value int\n Right *Tree\n}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Continue description on \u003ca href=\"javascript:click(\u0026#39;.next-page\u0026#39;)\" target=\"_self\"\u003enext page\u003c/a\u003e.\n \u003c/p\u003e\n \n\n","Files":[]},{"Title":"Exercise: Equivalent Binary Trees","Content":"\n \u003ch2\u003eExercise: Equivalent Binary Trees\u003c/h2\u003e\n \n \n \u003cp\u003e\n \u003cb\u003e1.\u003c/b\u003e Implement the \u003ccode\u003eWalk\u003c/code\u003e function.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003e2.\u003c/b\u003e Test the \u003ccode\u003eWalk\u003c/code\u003e function.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The function \u003ccode\u003etree.New(k)\u003c/code\u003e constructs a randomly-structured (but always sorted) binary tree holding the values \u003ccode\u003ek\u003c/code\u003e, \u003ccode\u003e2k\u003c/code\u003e, \u003ccode\u003e3k\u003c/code\u003e, ..., \u003ccode\u003e10k\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Create a new channel \u003ccode\u003ech\u003c/code\u003e and kick off the walker:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ego Walk(tree.New(1), ch)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, ..., 10.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003e3.\u003c/b\u003e Implement the \u003ccode\u003eSame\u003c/code\u003e function using \u003ccode\u003eWalk\u003c/code\u003e to determine whether \u003ccode\u003et1\u003c/code\u003e and \u003ccode\u003et2\u003c/code\u003e store the same values.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003e4.\u003c/b\u003e Test the \u003ccode\u003eSame\u003c/code\u003e function.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ccode\u003eSame(tree.New(1), tree.New(1))\u003c/code\u003e should return true, and \u003ccode\u003eSame(tree.New(1), tree.New(2))\u003c/code\u003e should return false.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The documentation for \u003ccode\u003eTree\u003c/code\u003e can be found \u003ca href=\"https://godoc.org/golang.org/x/tour/tree#Tree\" target=\"_blank\"\u003ehere\u003c/a\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-equivalent-binary-trees.go","Content":"package main\n\nimport \"golang.org/x/tour/tree\"\n\n// Walk walks the tree t sending all values\n// from the tree to the channel ch.\nfunc Walk(t *tree.Tree, ch chan int)\n\n// Same determines whether the trees\n// t1 and t2 contain the same values.\nfunc Same(t1, t2 *tree.Tree) bool\n\nfunc main() {\n}\n","Hash":"i2l8WC/EscB3twaI/V1sBdoyyRM="}]},{"Title":"sync.Mutex","Content":"\n \u003ch2\u003esync.Mutex\u003c/h2\u003e\n \n \n \u003cp\u003e\n We\u0026#39;ve seen how channels are great for communication among goroutines.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n But what if we don\u0026#39;t need communication? What if we just want to make sure only\n\n\n one goroutine can access a variable at a time to avoid conflicts?\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This concept is called \u003ci\u003emutual exclusion\u003c/i\u003e, and the conventional name for the data structure that provides it is \u003ci\u003emutex\u003c/i\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Go\u0026#39;s standard library provides mutual exclusion with\n\n\n \u003ca href=\"/pkg/sync/#Mutex\" target=\"_self\"\u003e\u003ccode\u003esync.Mutex\u003c/code\u003e\u003c/a\u003e and its two methods:\n \u003c/p\u003e\n \n\n \u003cul\u003e\n \n \u003cli\u003e\u003ccode\u003eLock\u003c/code\u003e\u003c/li\u003e\n \n \u003cli\u003e\u003ccode\u003eUnlock\u003c/code\u003e\u003c/li\u003e\n \n \u003c/ul\u003e\n\n \n \u003cp\u003e\n We can define a block of code to be executed in mutual exclusion by surrounding it\n\n\n with a call to \u003ccode\u003eLock\u003c/code\u003e and \u003ccode\u003eUnlock\u003c/code\u003e as shown on the \u003ccode\u003eInc\u003c/code\u003e method.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n We can also use \u003ccode\u003edefer\u003c/code\u003e to ensure the mutex will be unlocked as in the \u003ccode\u003eValue\u003c/code\u003e method.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"mutex-counter.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n)\n\n// SafeCounter is safe to use concurrently.\ntype SafeCounter struct {\n\tmu sync.Mutex\n\tv map[string]int\n}\n\n// Inc increments the counter for the given key.\nfunc (c *SafeCounter) Inc(key string) {\n\tc.mu.Lock()\n\t// Lock so only one goroutine at a time can access the map c.v.\n\tc.v[key]++\n\tc.mu.Unlock()\n}\n\n// Value returns the current value of the counter for the given key.\nfunc (c *SafeCounter) Value(key string) int {\n\tc.mu.Lock()\n\t// Lock so only one goroutine at a time can access the map c.v.\n\tdefer c.mu.Unlock()\n\treturn c.v[key]\n}\n\nfunc main() {\n\tc := SafeCounter{v: make(map[string]int)}\n\tfor i := 0; i \u003c 1000; i++ {\n\t\tgo c.Inc(\"somekey\")\n\t}\n\n\ttime.Sleep(time.Second)\n\tfmt.Println(c.Value(\"somekey\"))\n}\n","Hash":"gr5LuYzvEKKTXYO1vTn2QMlF5uQ="}]},{"Title":"Exercise: Web Crawler","Content":"\n \u003ch2\u003eExercise: Web Crawler\u003c/h2\u003e\n \n \n \u003cp\u003e\n In this exercise you\u0026#39;ll use Go\u0026#39;s concurrency features to parallelize a web crawler.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Modify the \u003ccode\u003eCrawl\u003c/code\u003e function to fetch URLs in parallel without fetching the same URL twice.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003ci\u003eHint\u003c/i\u003e: you can keep a cache of the URLs that have been fetched on a map, but maps alone are not\n\n\n safe for concurrent use!\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-web-crawler.go","Content":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Fetcher interface {\n\t// Fetch returns the body of URL and\n\t// a slice of URLs found on that page.\n\tFetch(url string) (body string, urls []string, err error)\n}\n\n// Crawl uses fetcher to recursively crawl\n// pages starting with url, to a maximum of depth.\nfunc Crawl(url string, depth int, fetcher Fetcher) {\n\t// TODO: Fetch URLs in parallel.\n\t// TODO: Don't fetch the same URL twice.\n\t// This implementation doesn't do either:\n\tif depth \u003c= 0 {\n\t\treturn\n\t}\n\tbody, urls, err := fetcher.Fetch(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfmt.Printf(\"found: %s %q\\n\", url, body)\n\tfor _, u := range urls {\n\t\tCrawl(u, depth-1, fetcher)\n\t}\n\treturn\n}\n\nfunc main() {\n\tCrawl(\"https://golang.org/\", 4, fetcher)\n}\n\n// fakeFetcher is Fetcher that returns canned results.\ntype fakeFetcher map[string]*fakeResult\n\ntype fakeResult struct {\n\tbody string\n\turls []string\n}\n\nfunc (f fakeFetcher) Fetch(url string) (string, []string, error) {\n\tif res, ok := f[url]; ok {\n\t\treturn res.body, res.urls, nil\n\t}\n\treturn \"\", nil, fmt.Errorf(\"not found: %s\", url)\n}\n\n// fetcher is a populated fakeFetcher.\nvar fetcher = fakeFetcher{\n\t\"https://golang.org/\": \u0026fakeResult{\n\t\t\"The Go Programming Language\",\n\t\t[]string{\n\t\t\t\"https://golang.org/pkg/\",\n\t\t\t\"https://golang.org/cmd/\",\n\t\t},\n\t},\n\t\"https://golang.org/pkg/\": \u0026fakeResult{\n\t\t\"Packages\",\n\t\t[]string{\n\t\t\t\"https://golang.org/\",\n\t\t\t\"https://golang.org/cmd/\",\n\t\t\t\"https://golang.org/pkg/fmt/\",\n\t\t\t\"https://golang.org/pkg/os/\",\n\t\t},\n\t},\n\t\"https://golang.org/pkg/fmt/\": \u0026fakeResult{\n\t\t\"Package fmt\",\n\t\t[]string{\n\t\t\t\"https://golang.org/\",\n\t\t\t\"https://golang.org/pkg/\",\n\t\t},\n\t},\n\t\"https://golang.org/pkg/os/\": \u0026fakeResult{\n\t\t\"Package os\",\n\t\t[]string{\n\t\t\t\"https://golang.org/\",\n\t\t\t\"https://golang.org/pkg/\",\n\t\t},\n\t},\n}\n","Hash":"B/FADMZ6HBiJeHh8jLlvxCXPbew="}]},{"Title":"Where to Go from here...","Content":"\n \u003ch2\u003eWhere to Go from here...\u003c/h2\u003e\n \n \n \u003cp\u003e\n You can get started by\n\n\n \u003ca href=\"/doc/install/\" target=\"_self\"\u003einstalling Go\u003c/a\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Once you have Go installed, the\n\n\n \u003ca href=\"/doc/\" target=\"_self\"\u003eGo Documentation\u003c/a\u003e is a great place to\n\n\n continue.\n\n\n It contains references, tutorials, videos, and more.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To learn how to organize and work with Go code, read \u003ca href=\"/doc/code\" target=\"_self\"\u003eHow to Write Go Code\u003c/a\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n If you need help with the standard library, see the \u003ca href=\"/pkg/\" target=\"_self\"\u003epackage reference\u003c/a\u003e. For help with the language itself, you might be surprised to find the \u003ca href=\"/ref/spec\" target=\"_self\"\u003eLanguage Spec\u003c/a\u003e is quite readable.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To further explore Go\u0026#39;s concurrency model, watch\n\n\n \u003ca href=\"https://www.youtube.com/watch?v=f6kdp27TYZs\" target=\"_blank\"\u003eGo Concurrency Patterns\u003c/a\u003e\n\n\n (\u003ca href=\"/talks/2012/concurrency.slide\" target=\"_self\"\u003eslides\u003c/a\u003e)\n\n\n and\n\n\n \u003ca href=\"https://www.youtube.com/watch?v=QDDwwePbDtw\" target=\"_blank\"\u003eAdvanced Go Concurrency Patterns\u003c/a\u003e\n\n\n (\u003ca href=\"/talks/2013/advconc.slide\" target=\"_self\"\u003eslides\u003c/a\u003e)\n\n\n and read the\n\n\n \u003ca href=\"/doc/codewalk/sharemem/\" target=\"_self\"\u003eShare Memory by Communicating\u003c/a\u003e\n\n\n codewalk.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To get started writing web applications, watch\n\n\n \u003ca href=\"https://vimeo.com/53221558\" target=\"_blank\"\u003eA simple programming environment\u003c/a\u003e\n\n\n (\u003ca href=\"/talks/2012/simple.slide\" target=\"_self\"\u003eslides\u003c/a\u003e)\n\n\n and read the\n\n\n \u003ca href=\"/doc/articles/wiki/\" target=\"_self\"\u003eWriting Web Applications\u003c/a\u003e tutorial.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ca href=\"/doc/codewalk/functions/\" target=\"_self\"\u003eFirst Class Functions in Go\u003c/a\u003e codewalk gives an interesting perspective on Go\u0026#39;s function types.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The \u003ca href=\"/blog/\" target=\"_self\"\u003eGo Blog\u003c/a\u003e has a large archive of informative Go articles.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Visit \u003ca href=\"/\" target=\"_self\"\u003ethe Go home page\u003c/a\u003e for more.\n \u003c/p\u003e\n \n\n","Files":[]}]} ,"flowcontrol":{"Title":"Flow control statements: for, if, else, switch and defer","Description":"Learn how to control the flow of your code with conditionals, loops, switches and defers.","Pages":[{"Title":"For","Content":"\n \u003ch2\u003eFor\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go has only one looping construct, the \u003ccode\u003efor\u003c/code\u003e loop.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The basic \u003ccode\u003efor\u003c/code\u003e loop has three components separated by semicolons:\n \u003c/p\u003e\n \n\n \u003cul\u003e\n \n \u003cli\u003ethe init statement: executed before the first iteration\u003c/li\u003e\n \n \u003cli\u003ethe condition expression: evaluated before every iteration\u003c/li\u003e\n \n \u003cli\u003ethe post statement: executed at the end of every iteration\u003c/li\u003e\n \n \u003c/ul\u003e\n\n \n \u003cp\u003e\n The init statement will often be a short variable declaration, and the\n\n\n variables declared there are visible only in the scope of the \u003ccode\u003efor\u003c/code\u003e\n\n\n statement.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The loop will stop iterating once the boolean condition evaluates to \u003ccode\u003efalse\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eNote:\u003c/b\u003e Unlike other languages like C, Java, or JavaScript there are no parentheses\n\n\n surrounding the three components of the \u003ccode\u003efor\u003c/code\u003e statement and the braces \u003ccode\u003e{ }\u003c/code\u003e are\n\n\n always required.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"for.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tsum := 0\n\tfor i := 0; i \u003c 10; i++ {\n\t\tsum += i\n\t}\n\tfmt.Println(sum)\n}\n","Hash":"xJO/6+FEIQikuVbnofxw9o7g3Ig="}]},{"Title":"For continued","Content":"\n \u003ch2\u003eFor continued\u003c/h2\u003e\n \n \n \u003cp\u003e\n The init and post statements are optional.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"for-continued.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tsum := 1\n\tfor ; sum \u003c 1000; {\n\t\tsum += sum\n\t}\n\tfmt.Println(sum)\n}\n","Hash":"1SQ3UcrOPXhbZIL80CcWqOUSGP4="}]},{"Title":"For is Go's \"while\"","Content":"\n \u003ch2\u003eFor is Go\u0026#39;s \u0026#34;while\u0026#34;\u003c/h2\u003e\n \n \n \u003cp\u003e\n At that point you can drop the semicolons: C\u0026#39;s \u003ccode\u003ewhile\u003c/code\u003e is spelled \u003ccode\u003efor\u003c/code\u003e in Go.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"for-is-gos-while.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tsum := 1\n\tfor sum \u003c 1000 {\n\t\tsum += sum\n\t}\n\tfmt.Println(sum)\n}\n","Hash":"0C6Q8vy+sOTo5FmeCSn0gOHKfis="}]},{"Title":"Forever","Content":"\n \u003ch2\u003eForever\u003c/h2\u003e\n \n \n \u003cp\u003e\n If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"forever.go","Content":"package main\n\nfunc main() {\n\tfor {\n\t}\n}\n","Hash":"LGPmerQM9dL5ipTYobVqMxgS2zc="}]},{"Title":"If","Content":"\n \u003ch2\u003eIf\u003c/h2\u003e\n \n \n \u003cp\u003e\n Go\u0026#39;s \u003ccode\u003eif\u003c/code\u003e statements are like its \u003ccode\u003efor\u003c/code\u003e loops; the expression need not be\n\n\n surrounded by parentheses \u003ccode\u003e( )\u003c/code\u003e but the braces \u003ccode\u003e{ }\u003c/code\u003e are required.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"if.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc sqrt(x float64) string {\n\tif x \u003c 0 {\n\t\treturn sqrt(-x) + \"i\"\n\t}\n\treturn fmt.Sprint(math.Sqrt(x))\n}\n\nfunc main() {\n\tfmt.Println(sqrt(2), sqrt(-4))\n}\n","Hash":"r6fhyVTMogkJiLiZwAdhwGl+kZM="}]},{"Title":"If with a short statement","Content":"\n \u003ch2\u003eIf with a short statement\u003c/h2\u003e\n \n \n \u003cp\u003e\n Like \u003ccode\u003efor\u003c/code\u003e, the \u003ccode\u003eif\u003c/code\u003e statement can start with a short statement to execute before the condition.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Variables declared by the statement are only in scope until the end of the \u003ccode\u003eif\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (Try using \u003ccode\u003ev\u003c/code\u003e in the last \u003ccode\u003ereturn\u003c/code\u003e statement.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"if-with-a-short-statement.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc pow(x, n, lim float64) float64 {\n\tif v := math.Pow(x, n); v \u003c lim {\n\t\treturn v\n\t}\n\treturn lim\n}\n\nfunc main() {\n\tfmt.Println(\n\t\tpow(3, 2, 10),\n\t\tpow(3, 3, 20),\n\t)\n}\n","Hash":"Qdj1mMXhmi0bxex0sdU6BzhPM+g="}]},{"Title":"If and else","Content":"\n \u003ch2\u003eIf and else\u003c/h2\u003e\n \n \n \u003cp\u003e\n Variables declared inside an \u003ccode\u003eif\u003c/code\u003e short statement are also available inside any\n\n\n of the \u003ccode\u003eelse\u003c/code\u003e blocks.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (Both calls to \u003ccode\u003epow\u003c/code\u003e return their results before the call to \u003ccode\u003efmt.Println\u003c/code\u003e\n\n\n in \u003ccode\u003emain\u003c/code\u003e begins.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"if-and-else.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc pow(x, n, lim float64) float64 {\n\tif v := math.Pow(x, n); v \u003c lim {\n\t\treturn v\n\t} else {\n\t\tfmt.Printf(\"%g \u003e= %g\\n\", v, lim)\n\t}\n\t// can't use v here, though\n\treturn lim\n}\n\nfunc main() {\n\tfmt.Println(\n\t\tpow(3, 2, 10),\n\t\tpow(3, 3, 20),\n\t)\n}\n","Hash":"QFGZZx7YHQyh1OOVlVLgXw7u0nY="}]},{"Title":"Exercise: Loops and Functions","Content":"\n \u003ch2\u003eExercise: Loops and Functions\u003c/h2\u003e\n \n \n \u003cp\u003e\n As a way to play with functions and loops, let\u0026#39;s implement a square root function: given a number x, we want to find the number z for which z² is most nearly x.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Computers typically compute the square root of x using a loop.\n\n\n Starting with some guess z, we can adjust z based on how close z² is to x,\n\n\n producing a better guess:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ez -= (z*z - x) / (2*z)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Repeating this adjustment makes the guess better and better\n\n\n until we reach an answer that is as close to the actual square root as can be.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Implement this in the \u003ccode\u003efunc Sqrt\u003c/code\u003e provided.\n\n\n A decent starting guess for z is 1, no matter what the input.\n\n\n To begin with, repeat the calculation 10 times and print each z along the way.\n\n\n See how close you get to the answer for various values of x (1, 2, 3, ...)\n\n\n and how quickly the guess improves.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Hint: To declare and initialize a floating point value,\n\n\n give it floating point syntax or use a conversion:\n \u003c/p\u003e\n \n\n \n \u003cpre\u003ez := 1.0\nz := float64(1)\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n Next, change the loop condition to stop once the value has stopped\n\n\n changing (or only changes by a very small amount).\n\n\n See if that\u0026#39;s more or fewer than 10 iterations.\n\n\n Try other initial guesses for z, like x, or x/2.\n\n\n How close are your function\u0026#39;s results to the \u003ca href=\"/pkg/math/#Sqrt\" target=\"_self\"\u003emath.Sqrt\u003c/a\u003e in the standard library?\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (\u003cb\u003eNote:\u003c/b\u003e If you are interested in the details of the algorithm, the z² − x above\n\n\n is how far away z² is from where it needs to be (x), and the division by 2z is the derivative\n\n\n of z², to scale how much we adjust z by how quickly z² is changing.\n\n\n This general approach is called \u003ca href=\"https://en.wikipedia.org/wiki/Newton%27s_method\" target=\"_blank\"\u003eNewton\u0026#39;s method\u003c/a\u003e.\n\n\n It works well for many functions but especially well for square root.)\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"exercise-loops-and-functions.go","Content":"package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc Sqrt(x float64) float64 {\n}\n\nfunc main() {\n\tfmt.Println(Sqrt(2))\n}\n","Hash":"gtNrJKxe1FGotKs4BtY3aDHG9hM="}]},{"Title":"Switch","Content":"\n \u003ch2\u003eSwitch\u003c/h2\u003e\n \n \n \u003cp\u003e\n A \u003ccode\u003eswitch\u003c/code\u003e statement is a shorter way to write a sequence of \u003ccode\u003eif - else\u003c/code\u003e statements.\n\n\n It runs the first case whose value is equal to the condition expression.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n Go\u0026#39;s switch is like the one in C, C++, Java, JavaScript, and PHP,\n\n\n except that Go only runs the selected case, not all the cases that follow.\n\n\n In effect, the \u003ccode\u003ebreak\u003c/code\u003e statement that is needed at the end of each case in those\n\n\n languages is provided automatically in Go.\n\n\n Another important difference is that Go\u0026#39;s switch cases need not\n\n\n be constants, and the values involved need not be integers.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"switch.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n)\n\nfunc main() {\n\tfmt.Print(\"Go runs on \")\n\tswitch os := runtime.GOOS; os {\n\tcase \"darwin\":\n\t\tfmt.Println(\"OS X.\")\n\tcase \"linux\":\n\t\tfmt.Println(\"Linux.\")\n\tdefault:\n\t\t// freebsd, openbsd,\n\t\t// plan9, windows...\n\t\tfmt.Printf(\"%s.\\n\", os)\n\t}\n}\n","Hash":"ssXYUVr8b0W+UIdqULwjIXe5EIs="}]},{"Title":"Switch evaluation order","Content":"\n \u003ch2\u003eSwitch evaluation order\u003c/h2\u003e\n \n \n \u003cp\u003e\n Switch cases evaluate cases from top to bottom, stopping when a case succeeds.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n (For example,\n \u003c/p\u003e\n \n\n \n \u003cpre\u003eswitch i {\ncase 0:\ncase f():\n}\u003c/pre\u003e\n \n\n \n \u003cp\u003e\n does not call \u003ccode\u003ef\u003c/code\u003e if \u003ccode\u003ei==0\u003c/code\u003e.)\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n \u003cb\u003eNote:\u003c/b\u003e Time in the Go playground always appears to start at\n\n\n 2009-11-10 23:00:00 UTC, a value whose significance is left as an\n\n\n exercise for the reader.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"switch-evaluation-order.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tfmt.Println(\"When's Saturday?\")\n\ttoday := time.Now().Weekday()\n\tswitch time.Saturday {\n\tcase today + 0:\n\t\tfmt.Println(\"Today.\")\n\tcase today + 1:\n\t\tfmt.Println(\"Tomorrow.\")\n\tcase today + 2:\n\t\tfmt.Println(\"In two days.\")\n\tdefault:\n\t\tfmt.Println(\"Too far away.\")\n\t}\n}\n","Hash":"Hevv3n4U/ccdvgrd6ETU4Y2vgkg="}]},{"Title":"Switch with no condition","Content":"\n \u003ch2\u003eSwitch with no condition\u003c/h2\u003e\n \n \n \u003cp\u003e\n Switch without a condition is the same as \u003ccode\u003eswitch true\u003c/code\u003e.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n This construct can be a clean way to write long if-then-else chains.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"switch-with-no-condition.go","Content":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tt := time.Now()\n\tswitch {\n\tcase t.Hour() \u003c 12:\n\t\tfmt.Println(\"Good morning!\")\n\tcase t.Hour() \u003c 17:\n\t\tfmt.Println(\"Good afternoon.\")\n\tdefault:\n\t\tfmt.Println(\"Good evening.\")\n\t}\n}\n","Hash":"03rL/Cr+GvYFECOFbBJv5IX4Q9Y="}]},{"Title":"Defer","Content":"\n \u003ch2\u003eDefer\u003c/h2\u003e\n \n \n \u003cp\u003e\n A defer statement defers the execution of a function until the surrounding\n\n\n function returns.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n The deferred call\u0026#39;s arguments are evaluated immediately, but the function call\n\n\n is not executed until the surrounding function returns.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"defer.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tdefer fmt.Println(\"world\")\n\n\tfmt.Println(\"hello\")\n}\n","Hash":"2Z9b5KH9i2dp2TZu26N0xR/Af6Q="}]},{"Title":"Stacking defers","Content":"\n \u003ch2\u003eStacking defers\u003c/h2\u003e\n \n \n \u003cp\u003e\n Deferred function calls are pushed onto a stack. When a function returns, its\n\n\n deferred calls are executed in last-in-first-out order.\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n To learn more about defer statements read this\n\n\n \u003ca href=\"/blog/defer-panic-and-recover\" target=\"_self\"\u003eblog post\u003c/a\u003e.\n \u003c/p\u003e\n \n\n\t\n\t\t\n\t\n\n","Files":[{"Name":"defer-multi.go","Content":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"counting\")\n\n\tfor i := 0; i \u003c 10; i++ {\n\t\tdefer fmt.Println(i)\n\t}\n\n\tfmt.Println(\"done\")\n}\n","Hash":"BFzzho+ksu2wU+yyZOcnJ5z3kQg="}]},{"Title":"Congratulations!","Content":"\n \u003ch2\u003eCongratulations!\u003c/h2\u003e\n \n \n \u003cp\u003e\n You finished this lesson!\n \u003c/p\u003e\n \n\n \n \u003cp\u003e\n You can go back to the list of \u003ca href=\"/tour/list\" target=\"_self\"\u003emodules\u003c/a\u003e to find what to learn next, or continue with the \u003ca href=\"javascript:click(\u0026#39;.next-page\u0026#39;)\" target=\"_self\"\u003enext lesson\u003c/a\u003e.\n \u003c/p\u003e\n \n\n","Files":[]}]} }