Skip to content

Commit a541e3d

Browse files
authored
save
1 parent 8ae24a6 commit a541e3d

31 files changed

+2183
-0
lines changed

content/en/docs/README.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
[Go](https://go.dev/) is an open-source programming language designed for building scalable, secure, and reliable software. Please read the [official documentation](https://go.dev/doc/tutorial/getting-started) to learn more.
2+
3+
*Go by Example* is a hands-on introduction to Go using annotated example programs. Check out the [first example](hello-world.md) or browse the full list below.
4+
5+
Unless stated otherwise, the examples here assume the [latest major release Go](https://go.dev/doc/devel/release) and may use new language features. If something isn't working, try upgrading to the latest version.
6+
7+
<br>
8+
9+
<style>
10+
/* Make draft links from included SUMMARY.md on README.md non-clickable. */
11+
#content a[href=""] {
12+
color: var(--sidebar-non-existant);;
13+
text-decoration: none;
14+
cursor: default;
15+
pointer-events: none;
16+
}
17+
</style>
18+
19+
{{#include SUMMARY.md:7:}}
20+
21+
### FAQ
22+
23+
#### I found a problem with the examples; what do I do?
24+
25+
We're very happy to fix problem reports and accept contributions! Please submit
26+
[an issue](https://github.com/jcbhmt/gobyexample.jcbhmr.com/issues) or send a Pull Request.
27+
See `CONTRIBUTING.md` for more details.
28+
29+
#### What version of Go is required to run these examples?
30+
31+
Given Go's strong [backwards compatibility guarantees](https://go.dev/doc/go1compat),
32+
we expect the vast majority of examples to work on the latest released version of Go
33+
as well as many older releases going back years.
34+
35+
That said, some examples show off new features added in recent releases; therefore,
36+
it's recommended to try running examples with the latest officially released Go version
37+
(see Go's [release history](https://go.dev/doc/devel/release) for details).
38+
39+
#### I'm getting output in a different order from the example. Is the example wrong?
40+
41+
Some of the examples demonstrate concurrent code which has a non-deterministic
42+
execution order. It depends on how the Go runtime schedules its goroutines and
43+
may vary by operating system, CPU architecture, or even Go version.
44+
45+
Similarly, examples that iterate over maps may produce items in a different order
46+
from what you're getting on your machine. This is because the order of iteration
47+
over maps in Go is [not specified and is not guaranteed to be the same from one
48+
iteration to the next](https://go.dev/ref/spec#RangeClause).
49+
50+
It doesn't mean anything is wrong with the example. Typically the code in these
51+
examples will be insensitive to the actual order of the output; if the code is
52+
sensitive to the order - that's probably a bug - so feel free to report it.

content/en/docs/for.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# For
2+
3+
```go,editable
4+
// `for` is Go's only looping construct. Here are
5+
// some basic types of `for` loops.
6+
7+
package main
8+
9+
import "fmt"
10+
11+
func main() {
12+
13+
// The most basic type, with a single condition.
14+
i := 1
15+
for i <= 3 {
16+
fmt.Println(i)
17+
i = i + 1
18+
}
19+
20+
// A classic initial/condition/after `for` loop.
21+
for j := 0; j < 3; j++ {
22+
fmt.Println(j)
23+
}
24+
25+
// Another way of accomplishing the basic "do this
26+
// N times" iteration is `range` over an integer.
27+
for i := range 3 {
28+
fmt.Println("range", i)
29+
}
30+
31+
// `for` without a condition will loop repeatedly
32+
// until you `break` out of the loop or `return` from
33+
// the enclosing function.
34+
for {
35+
fmt.Println("loop")
36+
break
37+
}
38+
39+
// You can also `continue` to the next iteration of
40+
// the loop.
41+
for n := range 6 {
42+
if n%2 == 0 {
43+
continue
44+
}
45+
fmt.Println(n)
46+
}
47+
}
48+
```
49+
50+
```sh
51+
$ go run for.go
52+
1
53+
2
54+
3
55+
0
56+
1
57+
2
58+
range 0
59+
range 1
60+
range 2
61+
loop
62+
1
63+
3
64+
5
65+
66+
# We'll see some other `for` forms later when we look at
67+
# `range` statements, channels, and other data
68+
# structures.
69+
```

content/en/docs/functions.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Functions
2+
3+
```go,editable
4+
// _Functions_ are central in Go. We'll learn about
5+
// functions with a few different examples.
6+
7+
package main
8+
9+
import "fmt"
10+
11+
// Here's a function that takes two `int`s and returns
12+
// their sum as an `int`.
13+
func plus(a int, b int) int {
14+
15+
// Go requires explicit returns, i.e. it won't
16+
// automatically return the value of the last
17+
// expression.
18+
return a + b
19+
}
20+
21+
// When you have multiple consecutive parameters of
22+
// the same type, you may omit the type name for the
23+
// like-typed parameters up to the final parameter that
24+
// declares the type.
25+
func plusPlus(a, b, c int) int {
26+
return a + b + c
27+
}
28+
29+
func main() {
30+
31+
// Call a function just as you'd expect, with
32+
// `name(args)`.
33+
res := plus(1, 2)
34+
fmt.Println("1+2 =", res)
35+
36+
res = plusPlus(1, 2, 3)
37+
fmt.Println("1+2+3 =", res)
38+
}
39+
```
40+
41+
```sh
42+
$ go run functions.go
43+
1+2 = 3
44+
1+2+3 = 6
45+
46+
# There are several other features to Go functions. One is
47+
# multiple return values, which we'll look at next.
48+
```

content/en/docs/generics.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Generics
2+
3+
```go,editable
4+
// Starting with version 1.18, Go has added support for
5+
// _generics_, also known as _type parameters_.
6+
7+
package main
8+
9+
import "fmt"
10+
11+
// As an example of a generic function, `SlicesIndex` takes
12+
// a slice of any `comparable` type and an element of that
13+
// type and returns the index of the first occurrence of
14+
// v in s, or -1 if not present. The `comparable` constraint
15+
// means that we can compare values of this type with the
16+
// `==` and `!=` operators. For a more thorough explanation
17+
// of this type signature, see [this blog post](https://go.dev/blog/deconstructing-type-parameters).
18+
// Note that this function exists in the standard library
19+
// as [slices.Index](https://pkg.go.dev/slices#Index).
20+
func SlicesIndex[S ~[]E, E comparable](s S, v E) int {
21+
for i := range s {
22+
if v == s[i] {
23+
return i
24+
}
25+
}
26+
return -1
27+
}
28+
29+
// As an example of a generic type, `List` is a
30+
// singly-linked list with values of any type.
31+
type List[T any] struct {
32+
head, tail *element[T]
33+
}
34+
35+
type element[T any] struct {
36+
next *element[T]
37+
val T
38+
}
39+
40+
// We can define methods on generic types just like we
41+
// do on regular types, but we have to keep the type
42+
// parameters in place. The type is `List[T]`, not `List`.
43+
func (lst *List[T]) Push(v T) {
44+
if lst.tail == nil {
45+
lst.head = &element[T]{val: v}
46+
lst.tail = lst.head
47+
} else {
48+
lst.tail.next = &element[T]{val: v}
49+
lst.tail = lst.tail.next
50+
}
51+
}
52+
53+
// AllElements returns all the List elements as a slice.
54+
// In the next example we'll see a more idiomatic way
55+
// of iterating over all elements of custom types.
56+
func (lst *List[T]) AllElements() []T {
57+
var elems []T
58+
for e := lst.head; e != nil; e = e.next {
59+
elems = append(elems, e.val)
60+
}
61+
return elems
62+
}
63+
64+
func main() {
65+
var s = []string{"foo", "bar", "zoo"}
66+
67+
// When invoking generic functions, we can often rely
68+
// on _type inference_. Note that we don't have to
69+
// specify the types for `S` and `E` when
70+
// calling `SlicesIndex` - the compiler infers them
71+
// automatically.
72+
fmt.Println("index of zoo:", SlicesIndex(s, "zoo"))
73+
74+
// ... though we could also specify them explicitly.
75+
_ = SlicesIndex[[]string, string](s, "zoo")
76+
77+
lst := List[int]{}
78+
lst.Push(10)
79+
lst.Push(13)
80+
lst.Push(23)
81+
fmt.Println("list:", lst.AllElements())
82+
}
83+
```
84+
85+
```sh
86+
$ go run generics.go
87+
index of zoo: 2
88+
list: [10 13 23]
89+
```

content/en/docs/goroutines.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Goroutines
2+
3+
```go,editable
4+
// A _goroutine_ is a lightweight thread of execution.
5+
6+
package main
7+
8+
import (
9+
"fmt"
10+
"time"
11+
)
12+
13+
func f(from string) {
14+
for i := 0; i < 3; i++ {
15+
fmt.Println(from, ":", i)
16+
}
17+
}
18+
19+
func main() {
20+
21+
// Suppose we have a function call `f(s)`. Here's how
22+
// we'd call that in the usual way, running it
23+
// synchronously.
24+
f("direct")
25+
26+
// To invoke this function in a goroutine, use
27+
// `go f(s)`. This new goroutine will execute
28+
// concurrently with the calling one.
29+
go f("goroutine")
30+
31+
// You can also start a goroutine for an anonymous
32+
// function call.
33+
go func(msg string) {
34+
fmt.Println(msg)
35+
}("going")
36+
37+
// Our two function calls are running asynchronously in
38+
// separate goroutines now. Wait for them to finish
39+
// (for a more robust approach, use a [WaitGroup](waitgroups)).
40+
time.Sleep(time.Second)
41+
fmt.Println("done")
42+
}
43+
```
44+
45+
```sh
46+
# When we run this program, we see the output of the
47+
# blocking call first, then the output of the two
48+
# goroutines. The goroutines' output may be interleaved,
49+
# because goroutines are being run concurrently by the
50+
# Go runtime.
51+
$ go run goroutines.go
52+
direct : 0
53+
direct : 1
54+
direct : 2
55+
goroutine : 0
56+
going
57+
goroutine : 1
58+
goroutine : 2
59+
done
60+
61+
# Next we'll look at a complement to goroutines in
62+
# concurrent Go programs: channels.
63+
```

content/en/docs/hello-world.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Hello World
2+
3+
```go,editable
4+
// Our first program will print the classic "hello world"
5+
// message. Here's the full source code.
6+
package main
7+
8+
import "fmt"
9+
10+
func main() {
11+
fmt.Println("hello world")
12+
}
13+
```
14+
15+
```sh
16+
# To run the program, put the code in `hello-world.go` and
17+
# use `go run`.
18+
$ go run hello-world.go
19+
hello world
20+
21+
# Sometimes we'll want to build our programs into
22+
# binaries. We can do this using `go build`.
23+
$ go build hello-world.go
24+
$ ls
25+
hello-world hello-world.go
26+
27+
# We can then execute the built binary directly.
28+
$ ./hello-world
29+
hello world
30+
31+
# Now that we can run and build basic Go programs, let's
32+
# learn more about the language.
33+
```

0 commit comments

Comments
 (0)