Skip to content
Snippets Groups Projects
presentation.Rmd 8.16 KiB
Newer Older
Laurent Modolo's avatar
Laurent Modolo committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
---
# SPDX-FileCopyrightText: 2022 Laurent Modolo
# 
# SPDX-License-Identifier: AGPL-3.0-or-later
title: "Formation Go"
author: "Laurent Modolo"
date: "2022/11/08"
output:
  beamer_presentation:
    df_print: tibble
    fig_caption: no
    highlight: tango
    latex_engine: xelatex
    slide_level: 1
    theme: metropolis
  ioslides_presentation:
    highlight: tango
  slidy_presentation:
    highlight: tango
classoption: aspectratio=169  
---



```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```


# Formation Go:   

- ARAMIS
- Sebastien Binet 
- Monday 26 September - Tuesday 27 September 2022 All Day
- https://tour.golang.org

\begin{center}
\href{https://github.com/sbinet/margo}{https://github.com/sbinet/margo}
\end{center}



# What is Go?

Go is a new, general-purpose programming language.

- Compiled
- Statically typed
- Concurrent
- Simple
- Productive

History:

- Project starts at Google in 2007 (by Griesemer, Pike, Thompson)
- Open source release in November 2009

# Install Go

[https://go.dev/doc/install](https://go.dev/doc/install)

```sh
mkdir -p $HOME/go
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$PATH
````

everything is in the `go` folder

# Install and run a go programm

```
go install -v github.com/sbinet/margo/cmd/margo-hello@latest
```

go install downloaded (cloned, in git speak) the whole `github.com/sbinet/margo` repository (under `$GOPATH/pkg/mod`) and compiled the `margo-hello` command. As the compilation was successful, it also installed the `margo-hello` command under `$GOPATH/bin`.


# The `go` tool

Compile and run code

```sh
go run hello.go
```

Test code

```sh
go test archive/zip
ok  	archive/zip	19.557s
```

Build the files in the current directory:

```sh
go build
```

Fetch and install the `websocket` package (in the current module):

```sh
go get golang.org/x/net/websocket
```

# Workspace

```
 go
├──  bin
│  ├──  margo
│  ├──  margo-hello
│  ├──  motion
│  ├──  ...
│  ├──  revive
│  └──  staticcheck
├──  pkg
│  ├──  mod
│  └──  sumdb
└──  src
   └──  github.com
```

- `bin` executable binaries
- `pkg` compiled object files
- `src` source code
    
# `pkg`

```sh
go install -v github.com/sbinet/margo/cmd/margo-hello@latest
```

- `go/pkg/mod/github.com/sbinet/margo@v0.0.0-20220927190215-3215db22d608`
- `go/bin/margo-hello`

# `src`

```sh
mkdir -p $GOPATH/src/gitbio.ens-lyon.fr/margo
cd $GOPATH/src/gitbio.ens-lyon.fr/margo
go mod init
go: creating new go.mod: module gitbio.ens-lyon.fr/margo # create a go.mod file
```

```
mkdir -p $GOPATH/src/gitbio.ens-lyon.fr/margo/hello
cp $GOPATH/pkg/mod/github.com/sbinet/margo@v0.0.0-20220927190215-3215db22d608/cmd/margo-hello/main.go $GOPATH/src/gitbio.ens-lyon.fr/margo/hello/
```

```
go install gitbio.ens-lyon.fr/margo/hello
hello
Hello MarGo!
```

# Langage

- primitive types

```go
int, uint, uint8, ..., uint64, int8, ... int64
bool, string
float32, float64
complex64, complex128
```

- structs

```go
struct {
	Name string
	Year int
}
```

# Langage

- arrays and slices
```go
[3]string, []float64
```

- maps
```go
map[string]int
```

- pointers
```go
*int, *Person
```


# Declaration

Normal declaration:

```go
var text string = "hello"
```

You can omit types:

```go
var text = "hello"
```

```go
text := "hello" //create and init
```

This code won't compile:

```
var freezing Fahrenheit = 32
var boiling Celsius = 100
sauna := (freezing + boiling) / 2
```

There's no implicit numeric conversion in Go.

# Functions

A sum function:

```go
func sum(a int, b int) int {
	return a + b
}
```

A function with multiple return values:

Made clearer by naming the return values:
```go
func divMod(a, b int) (quo, rem int) {
	return a / b, a % b
}
```

# Pointers

Go has pointers:

```go
var p *int
p = new(int)
```

But no pointer arithmetics:

```go
var p *int = &a[0]
var q = p+2            // invalid
```

There's `new` but there's no `delete`.

Memory is garbaged collected after it's no longer accessible.


# Memory allocation

The compiler decides where to allocate based on escape analysis.

Using `new` doesn't imply using the heap:

`stack.go`:
```go
func get() int {
    n := new(int)
    return *n
}
````

And not all values in the heap are created with `new`:

`heap.go`:
```go
func get() *int {
    n := 4
    return &n
}
```

# Packages & Imports

Every [[https://golang.org/][Go]] program is made up of packages.

Programs start running in `package` `main`.

This program is using the packages with import paths `"fmt"` and `"math/rand"`.

By convention, the package name is the same as the last element of the import path.
For instance, the `"math/rand"` package comprises files that begin with the statement `package` `rand`.

```
package main

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println("My favorite number is", rand.Intn(10))
}
```

# Exported names

In [[https://golang.org/][Go]], a name is *exported* if it begins with a *capital* *letter*.
For example, `Pizza` is an exported name, as is `Pi`, which is exported from the `math` package.

`pizza` and `pi` do not start with a capital letter, so they are not exported.

When importing a package, you can refer only to its exported names.
Any "unexported" names are not accessible from outside the package.

Run the code. Notice the error message.

# Documentation

Browsing documentation is performed with `go` `doc`.

```sh
go doc os | less

PACKAGE DOCUMENTATION

package os
  import "os"

  Package os provides a platform-independent interface to operating system
  functionality. The design is Unix-like, although the error handling is
  Go-like; failing calls return values of type error rather than error
  numbers. Often, more information is available within the error. For
  example, if a call that takes a file name fails, such as Open or Stat,
  the error will include the failing file name when printed and will be of
  type *PathError, which may be unpacked for more information.
```

# Documentation

Browsing documentation is performed with `go` `doc`.

```sh
go doc os File | less

type File struct {
    // contains filtered or unexported fields
}
    File represents an open file descriptor.

func Create(name string) (file *File, err error)
    Create creates the named file mode 0666 (before umask), truncating it if
    it already exists. If successful, methods on the returned File can be
    used for I/O; the associated file descriptor has mode O_RDWR. If there
    is an error, it will be of type *PathError.

func Open(name string) (file *File, err error)
    Open opens the named file for reading. If successful, methods on the
    returned file can be used for reading; the associated file descriptor
    has mode O_RDONLY. If there is an error, it will be of type *PathError.
```

# Goroutines

What is a goroutine? It's an independently executing function, launched by a go statement.

It has its own call stack, which grows and shrinks as required.

It's very cheap. It's practical to have thousands, even hundreds of thousands of goroutines.

It's not a thread.

There might be only one thread in a program with thousands of goroutines.

Instead, goroutines are multiplexed dynamically onto threads as needed to keep all the goroutines running.

But if you think of it as a very cheap thread, you won't be far off


# Goroutines

```go
func main() {
	boring("boring!")
}

func boring(msg string) {
	for i := 0; ; i++ {
		fmt.Println(msg, i)
		time.Sleep(time.Second)
	}
}
```

# Channels

A channel in Go provides a connection between two goroutines, allowing them to communicate.

```go
func main() {
	c := make(chan string)
	go boring("boring!", c)
	for i := 0; i < 5; i++ {
		fmt.Printf("You say: %q\n", <-c) // Receive expression is just a value.
	}
}
```

# Channels

A channel in Go provides a connection between two goroutines, allowing them to communicate.
```go
func boring(msg string, c chan string) {
	for i := 0; ; i++ {
		c <- fmt.Sprintf("%s %d", msg, i) // Expression to be sent can be any suitable value.
		time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
	}
}
```

# For scientific development

https://github.com/gonum

\begin{center}
\href{https://doc.rust-lang.org/book/}{https://doc.rust-lang.org/book/}
\end{center}