/static/index.html

https://code.google.com/p/go-tour-it/ · HTML · 2323 lines · 1986 code · 329 blank · 8 comment · 0 complexity · e6160f3d6dac728a3d2d7c04f0c4bf3b MD5 · raw file

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
  4. <title>Un Tour nel Go</title>
  5. <!-- jQuery -->
  6. <script src="static/jquery.js"></script>
  7. <!-- Fonts -->
  8. <link href='http://fonts.googleapis.com/css?family=Droid+Serif&v1' rel='stylesheet' type='text/css'>
  9. <link href='http://fonts.googleapis.com/css?family=Droid+Sans&v1' rel='stylesheet' type='text/css'>
  10. <link href='http://fonts.googleapis.com/css?family=Droid+Sans+Mono&v1' rel='stylesheet' type='text/css'>
  11. <!-- Playground -->
  12. <link rel="stylesheet" href="/static/codemirror/lib/codemirror.css">
  13. <script src="/static/codemirror/lib/codemirror.js"></script>
  14. <link rel="stylesheet" href="/static/codemirror/theme/default.css">
  15. <script src="static/playground.js"></script>
  16. <!-- Tour -->
  17. <link rel="stylesheet" href="static/tour.css" charset="utf-8">
  18. <script src="static/mode.js"></script>
  19. <script src="static/tour.js"></script>
  20. </head>
  21. <body class="loading">
  22. <!-- Top bar -->
  23. <h2 id="slidenum"></h2>
  24. <div id="topnav" class="nav">
  25. <button id="tocbtn">Indice</button>
  26. <button id="codetr">Correggi*</button>
  27. </div>
  28. <h1>Un Tour nel Go (traduzione: 30%)</h1>
  29. <!-- Loading message -->
  30. <div id="loading">
  31. Caricamento schede...
  32. </div>
  33. <!-- Table of Contents -->
  34. <ol id="toc"></ol>
  35. <div id="slides" class="slides"><!-- begin slides -->
  36. <div class="toc">Benvenuto</div>
  37. <div class="slide">
  38. <h2>Ciao, 世界</h2>
  39. <p>
  40. Benvenuto nel tour del
  41. <a target="_blank" href="http://golang.org/">Linguaggio di Programmazione Go</a>.
  42. <p>
  43. Il tour è diviso in tre sezioni. Alla fine di ogni sezione
  44. c'è una serie di esercizi da svolgere.
  45. <p>
  46. Il tour è interattivo. Clicca su Run (o premi Shift-Invio)
  47. per compilare e avviare il programma sul
  48. <span class="appengineMode">server remoto.</span>
  49. <span class="localMode">tuo computer.</span>
  50. Il risultato apparirà sotto il codice.
  51. <p>
  52. I programmi di esempio evidenziano i diversi aspetti di Go.
  53. I programmi nel tour sono punti di partenza per le tue sperimentazioni.
  54. <p>
  55. Modifica il programma e avvialo ancora.
  56. <p>
  57. Quando credi di essere pronto, clicca su Next o premi PageDown (Pag Giù).
  58. <div>
  59. package main
  60. import "fmt"
  61. func main() {
  62. fmt.Println("Ciao, 世界")
  63. }
  64. </div>
  65. </div>
  66. <div class="slide nocode appengineMode">
  67. <h2>Go offline</h2>
  68. <p>
  69. Questo tour è disponibile anche come programma indipendente,
  70. usabile senza connessione a internet.
  71. <p>
  72. Il tour offline è più veloce nell'avviare e gestire il codice di esempio
  73. e include esercizi che non sono disponibili nella versione online.
  74. <p>
  75. Prima di avviare il tour in locale
  76. <a target="_blank" href="http://golang.org/doc/install.html">installa Go</a> (l'ultima release, <code>release.r60</code>),
  77. quindi usa
  78. <a target="_blank" href="http://golang.org/cmd/goinstall/">goinstall</a>
  79. per installare
  80. <a target="_blank" href="http://code.google.com/p/go-tour/">gotour</a>:
  81. <pre> goinstall go-tour.googlecode.com/hg/gotour</pre>
  82. <p>
  83. e avvia l'eseguibile <code>gotour</code>.
  84. <p>
  85. Altrimenti, fai clic sul pulsante "Next" o premi PagGiù per continuare.
  86. <p>
  87. <i>(Puoi tornare a queste istruzioni in qualsiasi momento facendo clic sul pulsante "Indice")</i>
  88. </div>
  89. <div class="slide nocode appengineMode">
  90. <h2>Go nella tua lingua</h2>
  91. <p>
  92. Il tour è disponibile in altre lingue:
  93. <ul>
  94. <li><a href="http://go-tour-jp.appspot.com/">Giapponese &mdash; 日本語</a></li>
  95. <li><a href="http://go-tour-kr.appspot.com/">Coreano &mdash; 한국어</a></li>
  96. <li><a href="http://go-tour-it.appspot.com/">Italiano</a>
  97. <a href="http://code.google.com/p/go-tour-it/source/browse/static/index.html">(contribuisci)</a>
  98. </li>
  99. </ul>
  100. <p>
  101. (Se si desidera tradurre il tour in un'altra lingua, basta scaricare i sorgenti da<br>
  102. <code>https://go-tour.googlecode.com/hg</code>, tradurre <code>static/index.html</code> e
  103. distribuirlo su App Engine utilizzando le istruzioni nel file <code>appengine/README</code>.)
  104. <p>
  105. Fare clic sul pulsante "Next" o PagGiù per continuare.
  106. </div>
  107. <div class="toc">Introduzione</div>
  108. <div class="slide">
  109. <h2>Packages (Pacchetti)</h2>
  110. <p>
  111. Ogni programma Go è costituito da Pacchetti.
  112. <p>
  113. I programmi iniziano a caricarsi dal pacchetto <code>main</code>.
  114. <p>
  115. Questo programma utilizza i pacchetti <code>"fmt"</code> e <code>"math"</code>
  116. infatti sono nel percorso di importazione.
  117. <p>
  118. Per convenzione, il nome del pacchetto è lo stesso dell'ultimo
  119. elemento del percorso di importazione.(?)
  120. <div>
  121. package main
  122. import (
  123. "fmt"
  124. "math"
  125. )
  126. func main() {
  127. fmt.Println("Buon", math.Pi, "day")
  128. }
  129. </div>
  130. </div>
  131. <div class="slide">
  132. <h2>Imports</h2>
  133. <p>
  134. Questo codice raggruppa gli Imports in una parentesi, il metodo di importazione "scomposto".
  135. Si possono anche scrivere più istruzioni import, come:
  136. <pre>
  137. import "fmt"
  138. import "math"
  139. </pre>
  140. ma è di comune utilizzo il metodo "scomposto" per eliminare il disordine.
  141. <div>
  142. package main
  143. import (
  144. "fmt"
  145. "math"
  146. )
  147. func main() {
  148. fmt.Printf("Adesso hai %g problemi.",
  149. math.Nextafter(2, 3))
  150. }
  151. </div>
  152. </div>
  153. <div class="slide">
  154. <h2>Exported Names</h2>
  155. <p>
  156. Dopo aver importato un pacchetto, è possibile fare riferimento ai suoi nomi.
  157. <p>
  158. In Go, un nome viene esportato se inizia con la lettera maiuscola.
  159. <p>
  160. <code>Pi</code> è un nome esportato, come <code>PI</code>.
  161. Il nome <code>pi</code> non è esportato.
  162. <p>
  163. Esegui il codice. Quindi rinomina <code>math.pi</code> in <code>math.Pi</code> e riprova.
  164. <div>
  165. package main
  166. import (
  167. "fmt"
  168. "math"
  169. )
  170. func main() {
  171. fmt.Println(math.pi)
  172. }
  173. </div>
  174. </div>
  175. <div class="slide">
  176. <h2>Funzioni</h2>
  177. <p>
  178. Una funzione può assumere zero o più argomenti.
  179. <p>
  180. In questo esempio, <code>add</code> accetta due parametri di tipo <code>int</code>.
  181. <p>
  182. Si noti che il tipo viene <i>dopo</i> il nome della variabile.
  183. <p>
  184. (Per maggiori informazioni sul funzionamento dei tipi, si veda questo <a target="_blank" href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">post del blog</a>)
  185. <div>
  186. package main
  187. import "fmt"
  188. func add(x int, y int) int {
  189. return x + y
  190. }
  191. func main() {
  192. fmt.Println(add(42, 13))
  193. }
  194. </div>
  195. </div>
  196. <div class="slide">
  197. <h2>Funzioni</h2>
  198. <p>
  199. Quando due o più nomi consecutivi condividono il tipo,
  200. è possibile omettere il tipo da tutti tranne l'ultimo.
  201. <p>
  202. In questo esempio, abbiamo accorciato
  203. <pre>x int, y int</pre>
  204. <p>
  205. in
  206. <pre>x, y int</pre>
  207. <div>
  208. package main
  209. import "fmt"
  210. func add(x, y int) int {
  211. return x + y
  212. }
  213. func main() {
  214. fmt.Println(add(42, 13))
  215. }
  216. </div>
  217. </div>
  218. <div class="slide">
  219. <h2>Funzioni</h2>
  220. <p>
  221. Una funzione può restituire qualsiasi numero di risultati.
  222. <p>
  223. Questa funzione restituisce due stringhe.
  224. <div>
  225. package main
  226. import "fmt"
  227. func swap(x, y string) (string, string) {
  228. return y, x
  229. }
  230. func main() {
  231. a, b := swap("ciao", "mondo")
  232. fmt.Println(a, b)
  233. }
  234. </div>
  235. </div>
  236. <div class="slide">
  237. <h2>Funzioni</h2>
  238. <p>
  239. Le funzioni prendono parametri; in Go i risultati possono essere nominati e
  240. si comportano come variabili; questi sono chiamati "result parameters".
  241. <p>
  242. Se i "result parameters" sono stati nominati, un <code>return</code> senza argomenti
  243. restituisce i valori correnti dei risultati.
  244. <div>
  245. package main
  246. import "fmt"
  247. func split(sum int) (x, y int) {
  248. x = sum * 4/9
  249. y = sum - x
  250. return
  251. }
  252. func main() {
  253. fmt.Println(split(17))
  254. }
  255. </div>
  256. </div>
  257. <div class="slide">
  258. <h2>Variabili</h2>
  259. <p>
  260. L' istruzione <code>var</code> dichiara una lista di variabili.<br>
  261. Come negli elenchi di argomenti delle funzioni, il tipo è alla fine.
  262. <div>
  263. package main
  264. import "fmt"
  265. var x, y, z int
  266. var c, python, java bool
  267. func main() {
  268. fmt.Println(x, y, z, c, python, java)
  269. }
  270. </div>
  271. </div>
  272. <div class="slide">
  273. <h2>Variabili</h2>
  274. <p>
  275. Una dichiarazione var può includere gli inizializzatori, uno per ogni variabile.
  276. <p>
  277. Se un initializer è presente, il tipo può essere omesso;
  278. la variabile prenderà il tipo dell' inizializer.
  279. <div>
  280. package main
  281. import "fmt"
  282. var x, y, z int = 1, 2, 3
  283. var c, python, java = true, false, "no!"
  284. func main() {
  285. fmt.Println(x, y, z, c, python, java)
  286. }
  287. </div>
  288. </div>
  289. <div class="slide">
  290. <h2>Variabili</h2>
  291. <p>
  292. All'interno di una funzione, l'istruzione di assegnazione breve <code>:=</code>
  293. può essere usata al posto della dichiarazione breve <code>var</code>.
  294. <p>
  295. (Al di fuori di una funzione, ogni costrutto inizia con una
  296. parola chiave mentre l'istruzione := non è disponibile).
  297. <div>
  298. package main
  299. import "fmt"
  300. func main() {
  301. var x, y, z int = 1, 2, 3
  302. c, python, java := true, false, "no!"
  303. fmt.Println(x, y, z, c, python, java)
  304. }
  305. </div>
  306. </div>
  307. <div class="slide">
  308. <h2>Constanti</h2>
  309. <p>
  310. Le constanti vengono dichiarate come le variabili, ma con la parola-chiave <code>const</code>.
  311. <p>
  312. Le costanti possono essere stringhe, boolean o valori numerici.
  313. <div>
  314. package main
  315. import "fmt"
  316. const Pi = 3.14
  317. func main() {
  318. const World = "世界"
  319. fmt.Println("Hello", World)
  320. fmt.Println("Happy", Pi, "Day")
  321. const Truth = true
  322. fmt.Println("Go rules?", Truth)
  323. }
  324. </div>
  325. </div>
  326. <div class="slide">
  327. <h2>Costanti numeriche</h2>
  328. <p>
  329. Le costanti numeriche sono <i>valori</i> ad alta precisione.
  330. <p>
  331. Una costante senza tipo prende il tipo necessario dal suo contesto.
  332. <p>
  333. Prova a stampare anche <code>needInt(Big)</code>.
  334. <div>
  335. package main
  336. import "fmt"
  337. const (
  338. Big = 1<<100
  339. Small = Big>>99
  340. )
  341. func needInt(x int) int { return x*10 + 1 }
  342. func needFloat(x float64) float64 {
  343. return x*0.1
  344. }
  345. func main() {
  346. fmt.Println(needInt(Small))
  347. fmt.Println(needFloat(Small))
  348. fmt.Println(needFloat(Big))
  349. }
  350. </div>
  351. </div>
  352. <div class="slide">
  353. <h2>For</h2>
  354. <p>
  355. Go ha solo un costrutto per le operazioni cicliche:<br>
  356. il ciclo <code>for</code>.
  357. <p>
  358. Il ciclo <code>for</code> appare come in C o Java, salvo che
  359. le parentesi tonde <code>( )</code> non esistono (non sono
  360. nemmeno opzionali) mentre le graffe <code>{ }</code> sono obbligatorie.
  361. <div>
  362. package main
  363. import "fmt"
  364. func main() {
  365. sum := 0
  366. for i := 0; i < 10; i++ {
  367. sum += i
  368. }
  369. fmt.Println(sum)
  370. }
  371. </div>
  372. </div>
  373. <div class="slide">
  374. <h2>For</h2>
  375. <p>
  376. Come in C o Java, è possibile lasciare le dichiarazioni pre e post vuote.
  377. <div>
  378. package main
  379. import "fmt"
  380. func main() {
  381. sum := 1
  382. for ; sum < 1000; {
  383. sum += sum
  384. }
  385. fmt.Println(sum)
  386. }
  387. </div>
  388. </div>
  389. <div class="slide">
  390. <h2>For</h2>
  391. <p>
  392. A questo punto è possibile eliminare i punti-virgola:
  393. Per ottenere ciò che in C avremmo scritto <code>while</code> in Go scriviamo <code>for</code>.
  394. <div>
  395. package main
  396. import "fmt"
  397. func main() {
  398. sum := 1
  399. for sum < 1000 {
  400. sum += sum
  401. }
  402. fmt.Println(sum)
  403. }
  404. </div>
  405. </div>
  406. <div class="slide">
  407. <h2>For</h2>
  408. <p>
  409. Se si omette la condizione del ciclo, il ciclo continua per sempre.
  410. <div>
  411. package main
  412. func main() {
  413. for ; ; {
  414. }
  415. }
  416. </div>
  417. </div>
  418. <div class="slide">
  419. <h2>For</h2>
  420. <p>
  421. E senza condizioni, i punti-virgola possono essere omessi.
  422. Ecco come appare un ciclo infinito compatto.
  423. <div>
  424. package main
  425. func main() {
  426. for {
  427. }
  428. }
  429. </div>
  430. </div>
  431. <div class="slide">
  432. <h2>If</h2>
  433. <p>
  434. L'istruzione <code>if</code> è si comporta come in C o Java,
  435. salvo che le parentesi tonde <code>( )</code> non esistono (non sono nemmeno opzionali)
  436. e le graffe <code>{ }</code> sono obbligatorie.
  437. <p>
  438. (Ti ricorda qualcosa?)
  439. <div>
  440. package main
  441. import (
  442. "fmt"
  443. "math"
  444. )
  445. func sqrt(x float64) string {
  446. if x < 0 {
  447. return sqrt(-x) + "i"
  448. }
  449. return fmt.Sprint(math.Sqrt(x))
  450. }
  451. func main() {
  452. fmt.Println(sqrt(2), sqrt(-4))
  453. }
  454. </div>
  455. </div>
  456. <div class="slide">
  457. <h2>If</h2>
  458. <p>
  459. Come <code>for</code>, l'istruzione <code>if</code> può iniziare
  460. con una breve dichiarazione da eseguire prima della condizione.
  461. <p>
  462. Le variabili dichiarate dalla dichiarazione sono disponibili solo fino alla fine del <code>if</code>.
  463. <p>
  464. (Prova ad usare <code>v</code> nell'ultima istruzione <code>return</code>.)
  465. <div>
  466. package main
  467. import (
  468. "fmt"
  469. "math"
  470. )
  471. func pow(x, n, lim float64) float64 {
  472. if v := math.Pow(x, n); v < lim {
  473. return v
  474. }
  475. return lim
  476. }
  477. func main() {
  478. fmt.Println(
  479. pow(3, 2, 10),
  480. pow(3, 3, 20),
  481. )
  482. }
  483. </div>
  484. </div>
  485. <div class="slide">
  486. <h2>If</h2>
  487. <p>
  488. Le variabili dichiarate all'interno di una istruzione <code>if</code>
  489. sono disponibili anche in una qualsiasi dei blocchi <code>else</code>.
  490. <div>
  491. package main
  492. import (
  493. "fmt"
  494. "math"
  495. )
  496. func pow(x, n, lim float64) float64 {
  497. if v := math.Pow(x, n); v < lim {
  498. return v
  499. } else {
  500. fmt.Printf("%g >= %g\n", v, lim)
  501. }
  502. // can't use v here, though
  503. return lim
  504. }
  505. func main() {
  506. fmt.Println(
  507. pow(3, 2, 10),
  508. pow(3, 3, 20),
  509. )
  510. }
  511. </div>
  512. </div>
  513. <div class="slide">
  514. <h2>Tipi di base</h2>
  515. <p>
  516. I tipi di base di Go sono:
  517. <pre>
  518. bool
  519. string
  520. int int8 int16 int32 int64
  521. uint uint8 uint16 uint32 uint64 uintptr
  522. float32 float64
  523. complex64 complex128
  524. </pre>
  525. <div>
  526. package main
  527. import (
  528. "cmath"
  529. "fmt"
  530. )
  531. var (
  532. ToBe bool = false
  533. MaxInt uint64 = 1<<64 - 1
  534. z complex128 = cmath.Sqrt(-5+12i)
  535. )
  536. func main() {
  537. const f = "%T(%v)\n"
  538. fmt.Printf(f, ToBe, ToBe)
  539. fmt.Printf(f, MaxInt, MaxInt)
  540. fmt.Printf(f, z, z)
  541. }
  542. </div>
  543. </div>
  544. <div class="slide">
  545. <h2>Structs (strutture)</h2>
  546. <p>
  547. Una <code>struct</code> è un insieme di campi.
  548. <p>
  549. (E le dichiarazioni <code>type</code> si comportano come vi aspettereste.)
  550. <div>
  551. package main
  552. import "fmt"
  553. type Vertex struct {
  554. X int
  555. Y int
  556. }
  557. func main() {
  558. fmt.Println(Vertex{1, 2})
  559. }
  560. </div>
  561. </div>
  562. <div class="slide">
  563. <h2>Struct Fields (Campi Struttura)</h2>
  564. <p>
  565. Un Struct field è accessibile tramite un punto.
  566. <div>
  567. package main
  568. import "fmt"
  569. type Vertex struct {
  570. X int
  571. Y int
  572. }
  573. func main() {
  574. v := Vertex{1, 2}
  575. v.X = 4
  576. fmt.Println(v.X)
  577. }
  578. </div>
  579. </div>
  580. <div class="slide">
  581. <h2>Pointers (Puntatori)</h2>
  582. <p>
  583. Go utilizza i puntatori, ma non l'aritmetica dei puntatori.
  584. <p>
  585. I campi struct sono accessibili tramite puntatori struct.<br>
  586. L'indirezione attraverso il puntatore è trasparente.
  587. <div>
  588. package main
  589. import "fmt"
  590. type Vertex struct {
  591. X int
  592. Y int
  593. }
  594. func main() {
  595. p := Vertex{1, 2}
  596. q := &p
  597. q.X = 1e9
  598. fmt.Println(p)
  599. }
  600. </div>
  601. </div>
  602. <div class="slide">
  603. <h2>Struct Literals (letterali)</h2>
  604. <p>
  605. Una struttura letterale denota un valore struct appena allocato elencando i valori dei suoi campi.
  606. <p>
  607. Si possono elencare solo un sottoinsieme di campi utilizzando la sintassi <code>Name:</code>.
  608. (L'ordine dei campi di nome è irrilevante)
  609. <p>
  610. Il prefisso specifico <code>&</code> costituisce un puntatore ad una struct letterale.
  611. <div>
  612. package main
  613. import "fmt"
  614. type Vertex struct {
  615. X, Y int
  616. }
  617. var (
  618. p = Vertex{1, 2} // has type Vertex
  619. q = &Vertex{1, 2} // has type *Vertex
  620. r = Vertex{X: 1} // Y:0 is implicit
  621. s = Vertex{} // X:0 and Y:0
  622. )
  623. func main() {
  624. fmt.Println(p, q, r, s)
  625. }
  626. </div>
  627. </div>
  628. <div class="slide">
  629. <h2>La funzione <code>new</code></h2>
  630. <p>
  631. L'espressione new(T) alloca un valore T azzerato e restituisce un puntatore ad esso.
  632. <pre>var t *T = new(T)</pre>
  633. <p>
  634. oppure
  635. <pre>t := new(T)</pre>
  636. <div>
  637. package main
  638. import "fmt"
  639. type Vertex struct {
  640. X, Y int
  641. }
  642. func main() {
  643. v := new(Vertex)
  644. fmt.Println(v)
  645. v.X, v.Y = 11, 9
  646. fmt.Println(v)
  647. }
  648. </div>
  649. </div>
  650. <div class="slide">
  651. <h2>Maps (Mappe)</h2>
  652. <p>
  653. Una map mappa (verbo mappare) chiavi per i valori.
  654. <p>
  655. <!-- TODO: empty part not true in compilers yet -->
  656. Le mappe devono essere creati con <code>make</code> (non <code>new</code>) prima dell'uso;
  657. il <code>nil</code> map è vuoto e non può essere assegnato.
  658. <div>
  659. package main
  660. import "fmt"
  661. type Vertex struct {
  662. Lat, Long float64
  663. }
  664. var m map[string]Vertex
  665. func main() {
  666. m = make(map[string]Vertex)
  667. m["Bell Labs"] = Vertex{
  668. 40.68433, 74.39967,
  669. }
  670. fmt.Println(m["Bell Labs"])
  671. }
  672. </div>
  673. </div>
  674. <div class="slide">
  675. <h2>Maps (letterali)</h2>
  676. <p>
  677. Map literals sono come le strutture letterali, ma le chiavi sono obbligatore.
  678. <div>
  679. package main
  680. import "fmt"
  681. type Vertex struct {
  682. Lat, Long float64
  683. }
  684. var m = map[string]Vertex{
  685. "Bell Labs": Vertex{
  686. 40.68433, -74.39967,
  687. },
  688. "Google": Vertex{
  689. 37.42202, -122.08408,
  690. },
  691. }
  692. func main() {
  693. fmt.Println(m)
  694. }
  695. </div>
  696. </div>
  697. <div class="slide">
  698. <h2>Maps</h2>
  699. <p>
  700. Se il tipo primcipale è solo un nome del tipo,
  701. è possibile omettere dagli elementi del letterale.
  702. <div>
  703. package main
  704. import "fmt"
  705. type Vertex struct {
  706. Lat, Long float64
  707. }
  708. var m = map[string]Vertex{
  709. "Bell Labs": {40.68433, -74.39967},
  710. "Google": {37.42202, -122.08408},
  711. }
  712. func main() {
  713. fmt.Println(m)
  714. }
  715. </div>
  716. </div>
  717. <div class="slide">
  718. <h2>Slices (Porzioni)</h2>
  719. <p>
  720. Una slice punta a un array di valori e comprende anche una lunghezza.
  721. <p>
  722. <code>[]T</code> è una slice con elementi del tipo <code>T</code>.
  723. <div>
  724. package main
  725. import "fmt"
  726. func main() {
  727. p := []int{2, 3, 5, 7, 11, 13}
  728. fmt.Println("p ==", p)
  729. for i := 0; i < len(p); i++ {
  730. fmt.Printf("p[%d] == %d\n",
  731. i, p[i])
  732. }
  733. }
  734. </div>
  735. </div>
  736. <div class="slide">
  737. <h2>Slices</h2>
  738. <p>
  739. Le Slices possono essere ripartite a loro volta, la creazione di un nuovo
  740. valore slice che punta allo stesso array.
  741. <p>
  742. L'espressione
  743. <pre>s[lo:hi]</pre>
  744. <p>
  745. restituisce una slice di elementi da <code>lo</code> attraverso <code>hi-1</code>, estremi inclusi.
  746. In questo modo,
  747. <pre>s[lo:lo]</pre>
  748. <p>
  749. è vuota e
  750. <pre>s[lo:lo+1]</pre>
  751. <p>
  752. ha un valore.
  753. <div>
  754. package main
  755. import "fmt"
  756. func main() {
  757. p := []int{2, 3, 5, 7, 11, 13}
  758. fmt.Println("p ==", p)
  759. fmt.Println("p[1:4] ==", p[1:4])
  760. // l'assenza dell' indice basso implica 0
  761. fmt.Println("p[:3] ==", p[:3])
  762. // l'assenza dell' indice alto implica len(s)
  763. fmt.Println("p[4:] ==", p[4:])
  764. }
  765. </div>
  766. </div>
  767. <div class="slide">
  768. <h2>Slices</h2>
  769. <p>
  770. Le Slices si creano con la funzione <code>make</code>. Funziona allocando
  771. un array azzerato e restituendo una slice che fa riferimento a tale array:
  772. <pre>
  773. a := make([]int, 5) // len(a)=5
  774. </pre>
  775. Le Slices hanno lunghezza (len) e capacità (cap). La capacità di una slice è
  776. la lunghezza massima che la slice può raggiungere all'interno dell' array sottostante.
  777. <p>
  778. Per specificare una capacità, basta passare un terzo argomento a <code>make</code>:
  779. <p>
  780. <pre>
  781. b := make([]int, 0, 5)
  782. // len(b)=0, cap(b)=5
  783. </pre>
  784. Le Slices possono essere alimentate dal "re-slicing" (fino alla loro capacità):
  785. <p>
  786. <pre>
  787. b = b[:cap(b)] // len(b)=5, cap(b)=5
  788. b = b[1:] // len(b)=4, cap(b)=4
  789. </pre>
  790. <div>
  791. package main
  792. import "fmt"
  793. func main() {
  794. a := make([]int, 5)
  795. printSlice("a", a)
  796. b := make([]int, 0, 5)
  797. printSlice("b", b)
  798. c := b[:2]
  799. printSlice("c", c)
  800. d := c[2:5]
  801. printSlice("d", d)
  802. }
  803. func printSlice(s string, x []int) {
  804. fmt.Printf("%s len=%d cap=%d %v\n",
  805. s, len(x), cap(x), x)
  806. }
  807. </div>
  808. </div>
  809. <div class="slide">
  810. <h2>Slices</h2>
  811. <p>
  812. The zero value of a slice is <code>nil</code>.
  813. <p>
  814. A nil slice has a length and capacity of 0.
  815. <p>
  816. <i>For more detail see the
  817. "<a target="_blank" href="http://blog.golang.org/2011/01/go-slices-usage-and-internals.html">Go Slices: usage and internals</a>"
  818. article.</i>
  819. <div>
  820. package main
  821. import "fmt"
  822. func main() {
  823. var z []int
  824. fmt.Println(z, len(z), cap(z))
  825. if z == nil {
  826. fmt.Println("nil!")
  827. }
  828. }
  829. </div>
  830. </div>
  831. <div class="slide">
  832. <h2>Functions</h2>
  833. <p>
  834. Functions are values too.
  835. <div>
  836. package main
  837. import (
  838. "fmt"
  839. "math"
  840. )
  841. func main() {
  842. hypot := func(x, y float64) float64 {
  843. return math.Sqrt(x*x + y*y)
  844. }
  845. fmt.Println(hypot(3, 4))
  846. }
  847. </div>
  848. </div>
  849. <div class="slide">
  850. <h2>Functions</h2>
  851. <p>
  852. And functions are full closures.
  853. <p>
  854. The <code>adder</code> function returns a closure.
  855. Each closure is bound to its own <code>sum</code> variable.
  856. <div>
  857. package main
  858. import "fmt"
  859. func adder() func(int) int {
  860. sum := 0
  861. return func(x int) int {
  862. sum += x
  863. return sum
  864. }
  865. }
  866. func main() {
  867. pos, neg := adder(), adder()
  868. for i := 0; i < 10; i++ {
  869. fmt.Println(
  870. pos(i),
  871. neg(-2*i),
  872. )
  873. }
  874. }
  875. </div>
  876. </div>
  877. <div class="slide">
  878. <h2>Range</h2>
  879. <p>
  880. The <code>range</code> form of the <code>for</code>
  881. loop iterates over a slice or map.
  882. <div>
  883. package main
  884. import "fmt"
  885. var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
  886. func main() {
  887. for i, v := range pow {
  888. fmt.Printf("2**%d = %d\n", i, v)
  889. }
  890. }
  891. </div>
  892. </div>
  893. <div class="slide">
  894. <h2>Range</h2>
  895. <p>
  896. You can skip the key or value by assigning to <code>_</code>.
  897. <p>
  898. If you only want the index, drop the
  899. &ldquo;<code>, value</code>&rdquo; entirely.
  900. <div>
  901. package main
  902. import "fmt"
  903. func main() {
  904. pow := make([]int, 10)
  905. for i := range pow {
  906. pow[i] = 1&lt;&lt;uint(i)
  907. }
  908. for _, value := range pow {
  909. fmt.Printf("%d\n", value)
  910. }
  911. }
  912. </div>
  913. </div>
  914. <div class="slide">
  915. <h2>Switch</h2>
  916. <p>
  917. You probably knew what <code>switch</code> was going to look like.
  918. <p>
  919. A case body breaks automatically, unless it ends with a <code>fallthrough</code> statement.
  920. <div>
  921. package main
  922. import (
  923. "fmt"
  924. "runtime"
  925. )
  926. func main() {
  927. fmt.Print("Go runs on ")
  928. switch os := runtime.GOOS; os {
  929. case "darwin":
  930. fmt.Println("OS X.")
  931. case "linux":
  932. fmt.Println("Linux.")
  933. default:
  934. // freebsd, openbsd,
  935. // plan9, windows...
  936. fmt.Printf("%s.", os)
  937. }
  938. }
  939. </div>
  940. </div>
  941. <div class="slide">
  942. <h2>Switch</h2>
  943. <p>
  944. Switch cases evaluate cases from top to bottom, stopping when a
  945. case succeeds.
  946. <p>
  947. (For example,
  948. <pre>
  949. switch i {
  950. case 0:
  951. case f():
  952. }</pre>
  953. <p>
  954. does not call <code>f</code> if <code>i==0</code>.)
  955. <div>
  956. package main
  957. import (
  958. "fmt"
  959. "time"
  960. )
  961. func main() {
  962. fmt.Println("When's Saturday?")
  963. today := time.LocalTime().Weekday
  964. switch time.Saturday {
  965. case today+0:
  966. fmt.Println("Today.")
  967. case today+1:
  968. fmt.Println("Tomorrow.")
  969. case today+2:
  970. fmt.Println("In two days.")
  971. default:
  972. fmt.Println("Too far away.")
  973. }
  974. }
  975. </div>
  976. </div>
  977. <div class="slide">
  978. <h2>Switch</h2>
  979. <p>
  980. Switch without a condition is the same as <code>switch true</code>.
  981. <div>
  982. package main
  983. import (
  984. "fmt"
  985. "time"
  986. )
  987. func main() {
  988. t := time.LocalTime()
  989. switch {
  990. case t.Hour < 12:
  991. fmt.Println("Good morning!")
  992. case t.Hour < 17:
  993. fmt.Println("Good afternoon.")
  994. default:
  995. fmt.Println("Good evening.")
  996. }
  997. }
  998. </div>
  999. </div>
  1000. <div class="slide">
  1001. <h2>Exercise: Loops and Functions</h2>
  1002. <p>
  1003. As a simple way to play with functions and loops, implement
  1004. the square root function using Newton's method.
  1005. <p>
  1006. In this case, Newton's method is to approximate <code>Sqrt(x)</code>
  1007. by picking a starting point <i>z</i> and then repeating:
  1008. <center>
  1009. <img src="https://chart.googleapis.com/chart?cht=tx&chl=z=z-\frac{z^2-x}{2z}">
  1010. </center>
  1011. <p>
  1012. To begin with, just repeat that calculation 10 times and see how close you
  1013. get to the answer for various values (1, 2, 3, ...).
  1014. <p>
  1015. Next, change the loop condition to stop once the value has stopped
  1016. changing (or only changes by a very small delta).
  1017. See if that's more or fewer iterations.
  1018. How close are you to the <a target="_blank" href="http://golang.org/pkg/math/#Sqrt">math.Sqrt</a>?
  1019. <p>
  1020. Hint: to declare and initialize a floating point value, give it
  1021. floating point syntax or use a conversion:
  1022. <pre>
  1023. z := float64(0)
  1024. z := 0.0
  1025. </pre>
  1026. <div>
  1027. package main
  1028. import (
  1029. "fmt"
  1030. )
  1031. func Sqrt(x float64) float64 {
  1032. }
  1033. func main() {
  1034. fmt.Println(Sqrt(2))
  1035. }
  1036. </div>
  1037. </div>
  1038. <div class="slide">
  1039. <h2>Exercise: Maps</h2>
  1040. <p>
  1041. Implement <code>WordCount</code>. It should return a map of the
  1042. counts of each &ldquo;word&rdquo; in the string <code>s</code>.
  1043. The <code>wc.Test</code> function runs a test suite against the
  1044. provided function and prints success or failure.
  1045. <p>
  1046. You might find <a target="_blank" href="http://golang.org/pkg/strings/#Fields">strings.Fields</a> helpful.
  1047. <div>
  1048. package main
  1049. import (
  1050. "<span class="appengineMode">tour</span><span class="localMode">go-tour.googlecode.com/hg</span>/wc"
  1051. )
  1052. func WordCount(s string) map[string]int {
  1053. return map[string]int{"x": 1}
  1054. }
  1055. func main() {
  1056. wc.Test(WordCount)
  1057. }
  1058. </div>
  1059. </div>
  1060. <div class="slide">
  1061. <h2>Exercise: Slices</h2>
  1062. <p>
  1063. Implement <code>Pic</code>. It should return a slice of length
  1064. <code>dy</code>, each element of which is a slice of <code>dx</code>
  1065. 8-bit unsigned integers. When you run the program, it will display
  1066. your picture, interpreting the integers as grayscale (well, bluescale)
  1067. values.
  1068. <p>
  1069. The choice of image is up to you.
  1070. Interesting functions include <code>x^y</code>, <code>(x+y)/2</code>, and <code>x*y</code>.
  1071. <p>
  1072. (You need to use a loop to allocate each <code>[]uint8</code> inside
  1073. the <code>[][]uint8</code>.)
  1074. <div>
  1075. package main
  1076. import "<span class="appengineMode">tour</span><span class="localMode">go-tour.googlecode.com/hg</span>/pic"
  1077. func Pic(dx, dy int) [][]uint8 {
  1078. }
  1079. func main() {
  1080. pic.Show(Pic)
  1081. }
  1082. </div>
  1083. </div>
  1084. <div class="slide">
  1085. <h2>Exercise: Fibonacci closure</h2>
  1086. <p>
  1087. Let's have some fun with functions.
  1088. <p>
  1089. Implement a <code>fibonacci</code> function that returns a function
  1090. (a closure) that returns successive fibonacci numbers.
  1091. <div>
  1092. package main
  1093. import "fmt"
  1094. // fibonacci is a function that returns
  1095. // a function that returns an int.
  1096. func fibonacci() func() int {
  1097. }
  1098. func main() {
  1099. f := fibonacci()
  1100. for i := 0; i < 10; i++ {
  1101. fmt.Println(f())
  1102. }
  1103. }
  1104. </div>
  1105. </div>
  1106. <div class="slide">
  1107. <h2>Advanced Exercise: Complex cube roots</h2>
  1108. <p>
  1109. Let's explore Go's built-in support for complex numbers via the
  1110. <code>complex64</code> and <code>complex128</code> types.
  1111. For cube roots, Newton's method amounts to repeating:
  1112. <center>
  1113. <img src="https://chart.googleapis.com/chart?cht=tx&chl=z=z-\frac{z^3-x}{3z^2}">
  1114. </center>
  1115. <p>
  1116. Find the cube root of 2, just to make sure the algorithm works.
  1117. There is a <a target="_blank" href="http://golang.org/pkg/cmath/#Pow">cmath.Pow</a> function.
  1118. <div>
  1119. package main
  1120. import "fmt"
  1121. func Cbrt(x complex128) complex128 {
  1122. }
  1123. func main() {
  1124. fmt.Println(Cbrt(2))
  1125. }
  1126. </div>
  1127. </div>
  1128. <div class="toc">Methods and Interfaces</div>
  1129. <div class="slide nocode">
  1130. <h2>Methods and Interfaces</h2>
  1131. </div>
  1132. <div class="slide">
  1133. <h2>Methods</h2>
  1134. <p>
  1135. Go does not have classes. However, you can define methods on struct
  1136. types.
  1137. <p>
  1138. The <i>method receiver</i> appears in its own argument list
  1139. between the <code>func</code> keyword and the method name.
  1140. <div>
  1141. package main
  1142. import (
  1143. "fmt"
  1144. "math"
  1145. )
  1146. type Vertex struct {
  1147. X, Y float64
  1148. }
  1149. func (v *Vertex) Abs() float64 {
  1150. return math.Sqrt(v.X*v.X + v.Y*v.Y)
  1151. }
  1152. func main() {
  1153. v := &Vertex{3, 4}
  1154. fmt.Println(v.Abs())
  1155. }
  1156. </div>
  1157. </div>
  1158. <div class="slide">
  1159. <h2>Methods</h2>
  1160. <p>
  1161. In fact, you can define a method on <i>any</i> type you define in your
  1162. package, not just structs.
  1163. <p>
  1164. You cannot define a method on a type from another package, or on a
  1165. basic type.
  1166. <div>
  1167. package main
  1168. import (
  1169. "fmt"
  1170. "math"
  1171. )
  1172. type MyFloat float64
  1173. func (f MyFloat) Abs() float64 {
  1174. if f < 0 {
  1175. return float64(-f)
  1176. }
  1177. return float64(f)
  1178. }
  1179. func main() {
  1180. f := MyFloat(-math.Sqrt2)
  1181. fmt.Println(f.Abs())
  1182. }
  1183. </div>
  1184. </div>
  1185. <div class="slide">
  1186. <h2>Methods with pointer receivers</h2>
  1187. <p>
  1188. Methods can be associated with a named type or a pointer
  1189. to a named type.
  1190. <p>
  1191. We just saw two <code>Abs</code> methods. One on the
  1192. <code>*Vertex</code> pointer type and the other on the
  1193. <code>MyFloat</code> value type.
  1194. <p>
  1195. There are two reasons to use a pointer receiver.
  1196. First, to avoid copying the value on each method call (more efficient
  1197. if the value type is a large struct). Second, so that the method can
  1198. modify the value that its receiver points to.
  1199. </ol>
  1200. <p>
  1201. Try changing the declarations of the <code>Abs</code> and
  1202. <code>Scale</code> methods to use <code>Vertex</code> as the
  1203. receiver, instead of <code>*Vertex</code>.
  1204. <p>
  1205. The <code>Scale</code> method has no effect when <code>v</code> is a
  1206. <code>Vertex</code>. <code>Scale</code> mutates <code>v</code>. When
  1207. <code>v</code> is a value (non-pointer) type, the method sees a copy of
  1208. the <code>Vertex</code> and cannot mutate the original value.
  1209. <p>
  1210. <code>Abs</code> works either way. It only reads <code>v</code>.
  1211. It doesn't matter whether it is reading the original value (through a
  1212. pointer) or a copy of that value.
  1213. <div>
  1214. package main
  1215. import (
  1216. "fmt"
  1217. "math"
  1218. )
  1219. type Vertex struct {
  1220. X, Y float64
  1221. }
  1222. func (v *Vertex) Scale(f float64) {
  1223. v.X = v.X * f
  1224. v.Y = v.Y * f
  1225. }
  1226. func (v *Vertex) Abs() float64 {
  1227. return math.Sqrt(v.X*v.X + v.Y*v.Y)
  1228. }
  1229. func main() {
  1230. v := &Vertex{3, 4}
  1231. v.Scale(5)
  1232. fmt.Println(v, v.Abs())
  1233. }
  1234. </div>
  1235. </div>
  1236. <div class="slide">
  1237. <h2>Interfaces</h2>
  1238. <p>
  1239. An interface type is defined by a set of methods.
  1240. <p>
  1241. A value of interface type can hold any value that
  1242. implements those methods.
  1243. <div>
  1244. package main
  1245. import (
  1246. "fmt"
  1247. "math"
  1248. )
  1249. type Abser interface {
  1250. Abs() float64
  1251. }
  1252. func main() {
  1253. var a Abser
  1254. f := MyFloat(-math.Sqrt2)
  1255. v := Vertex{3, 4}
  1256. a = f // a MyFloat implements Abser
  1257. a = &v // a *Vertex implements Abser
  1258. a = v // a Vertex, does NOT
  1259. // implement Abser
  1260. fmt.Println(a.Abs())
  1261. }
  1262. type MyFloat float64
  1263. func (f MyFloat) Abs() float64 {
  1264. if f < 0 {
  1265. return float64(-f)
  1266. }
  1267. return float64(f)
  1268. }
  1269. type Vertex struct {
  1270. X, Y float64
  1271. }
  1272. func (v *Vertex) Abs() float64 {
  1273. return math.Sqrt(v.X*v.X + v.Y*v.Y)
  1274. }
  1275. </div>
  1276. </div>
  1277. <div class="slide">
  1278. <h2>Interfaces</h2>
  1279. <p>
  1280. A type implements an interface by implementing the methods.
  1281. <p>
  1282. <i>There is no explicit declaration of intent.</i>
  1283. <p>
  1284. Implicit interfaces decouple implementation packages from the packages
  1285. that define the interfaces: neither depends on the other.
  1286. <p>
  1287. It also encourages the definition of precise interfaces, because you
  1288. don't have to find every implementation and tag it with the new
  1289. interface name.
  1290. <p>
  1291. <a target="_blank" href="http://golang.org/pkg/io/">Package io</a> defines <code>Reader</code> and <code>Writer</code>; you don't have to.
  1292. <div>
  1293. package main
  1294. import (
  1295. "fmt"
  1296. "os"
  1297. )
  1298. type Reader interface {
  1299. Read(b []byte) (n int, err os.Error)
  1300. }
  1301. type Writer interface {
  1302. Write(b []byte) (n int, err os.Error)
  1303. }
  1304. type ReadWriter interface {
  1305. Reader
  1306. Writer
  1307. }
  1308. func main() {
  1309. var w Writer
  1310. // os.Stdout implements Writer
  1311. w = os.Stdout
  1312. fmt.Fprintf(w, "hello, writer\n")
  1313. }
  1314. </div>
  1315. </div>
  1316. <div class="slide">
  1317. <h2>Errors</h2>
  1318. <p>
  1319. An error is anything that can describe itself:
  1320. <pre>
  1321. package os
  1322. type Error interface {
  1323. String() string
  1324. }
  1325. </pre>
  1326. <div>
  1327. package main
  1328. import (
  1329. "fmt"
  1330. "os"
  1331. "time"
  1332. )
  1333. type MyError struct {
  1334. When *time.Time
  1335. What string
  1336. }
  1337. func (e *MyError) String() string {
  1338. return fmt.Sprintf("at %v, %s",
  1339. e.When, e.What)
  1340. }
  1341. func run() os.Error {
  1342. return &MyError{
  1343. time.LocalTime(),
  1344. "it didn't work",
  1345. }
  1346. }
  1347. func main() {
  1348. if err := run(); err != nil {
  1349. fmt.Println(err)
  1350. }
  1351. }
  1352. </div>
  1353. </div>
  1354. <div class="slide">
  1355. <h2>Web servers</h2>
  1356. <p>
  1357. <a target="_blank" href="http://golang.org/pkg/http/">Package http</a> serves HTTP requests using any value
  1358. that implements <code>http.Handler</code>:
  1359. <pre>
  1360. package http
  1361. type Handler interface {
  1362. ServeHTTP(w ResponseWriter,
  1363. r *Request)
  1364. }
  1365. </pre>
  1366. <p>
  1367. In this example, the type <code>MyHandler</code> implements <code>http.Handler</code>.
  1368. <p>
  1369. <span class="localMode">
  1370. Visit <a href="http://localhost:4000/" target="_blank">http://localhost:4000/</a> to see the greeting.
  1371. </span>
  1372. <span class="appengineMode">
  1373. <b>Note:</b> This example won't run through the web-based tour user
  1374. interface. To try writing web servers you may want to
  1375. <a target="_blank" href="http://golang.org/doc/install.html">Install
  1376. Go</a>.
  1377. </span>
  1378. <div>
  1379. package main
  1380. import (
  1381. "fmt"
  1382. "http"
  1383. )
  1384. type Hello struct{}
  1385. func (h Hello) ServeHTTP(
  1386. w http.ResponseWriter,
  1387. r *http.Request) {
  1388. fmt.Fprint(w, "Hello!")
  1389. }
  1390. func main() {
  1391. var h Hello
  1392. http.ListenAndServe("localhost:4000",h)
  1393. }
  1394. </div>
  1395. </div>
  1396. <div class="slide">
  1397. <h2>Images</h2>
  1398. <p>
  1399. <a target="_blank" href="http://golang.org/pkg/image/#Image">Package image</a> defines the <code>Image</code>
  1400. interface:
  1401. <pre>
  1402. package image
  1403. type Image interface {
  1404. ColorModel() ColorModel
  1405. Bounds() Rectangle
  1406. At(x, y int) Color
  1407. }</pre>
  1408. <p>
  1409. (See <a target="_blank" href="http://golang.org/pkg/image/#Image">the
  1410. documentation</a> for all the details.)
  1411. <p>
  1412. <code>Color</code> and <code>ColorModel</code> are interfaces too,
  1413. but we'll ignore that by using the predefined implementations
  1414. <code>image.RGBAColor</code> and <code>image.RGBAColorModel</code>.
  1415. <div>
  1416. package main
  1417. import (
  1418. "fmt"
  1419. "image"
  1420. )
  1421. func main() {
  1422. m := image.NewRGBA(100, 100)
  1423. fmt.Println(m.Bounds())
  1424. fmt.Println(m.At(0, 0).RGBA())
  1425. }
  1426. </div>
  1427. </div>
  1428. <div class="slide">
  1429. <h2>Exercise: Errors</h2>
  1430. <p>
  1431. Copy your <code>Sqrt</code> function from the earlier exercises and
  1432. modify it to return an <code>os.Error</code> value.
  1433. <p>
  1434. <code>Sqrt</code> should return a non-nil error value when given a
  1435. negative number, as it doesn't support complex numbers.
  1436. <p>
  1437. Create a new type
  1438. <pre>
  1439. type ErrNegativeSqrt float64</pre>
  1440. <p>
  1441. and make it an <code>os.Error</code> by giving it a
  1442. <pre>
  1443. func (e ErrNegativeSqrt) String() string</pre>
  1444. <p>
  1445. method such that <code>ErrNegativeSqrt(-2).String()</code> returns
  1446. <code>"cannot Sqrt negative number: -2"</code>.
  1447. <p>
  1448. <b>Note:</b> a call to <code>fmt.Print(e)</code> inside the
  1449. <code>String</code> method will send the program into an infinite loop.
  1450. You can avoid this by converting <code>e</code> first:
  1451. <code>fmt.Print(float64(e))</code>. Why?
  1452. <p>
  1453. Change your <code>Sqrt</code> function to return an
  1454. <code>ErrNegativeSqrt</code> value when given a negative number.
  1455. <div>
  1456. package main
  1457. import (
  1458. "fmt"
  1459. "os"
  1460. )
  1461. func Sqrt(f float64) (float64, os.Error) {
  1462. return 0, nil
  1463. }
  1464. func main() {
  1465. fmt.Println(Sqrt(2))
  1466. fmt.Println(Sqrt(-2))
  1467. }
  1468. </div>
  1469. </div>
  1470. <div class="slide localMode">
  1471. <h2>Exercise: HTTP Handlers</h2>
  1472. <p>
  1473. Implement the following types and define ServeHTTP methods on them.
  1474. Register them to handle specific paths in your web server.
  1475. <pre>type String string
  1476. type Struct struct {
  1477. Greeting string
  1478. Punct string
  1479. Who string
  1480. }</pre>
  1481. <p>
  1482. For example, you should be able to register handlers using:
  1483. <pre>http.Handle("/string", String("I'm a frayed knot."))
  1484. http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})</pre>
  1485. <div>
  1486. package main
  1487. import (
  1488. "http"
  1489. )
  1490. func main() {
  1491. // your http.Handle calls here
  1492. http.ListenAndServe("localhost:4000", nil)
  1493. }
  1494. </div>
  1495. </div>
  1496. <div class="slide">
  1497. <h2>Exercise: Images</h2>
  1498. <p>
  1499. Remember the picture generator you wrote earlier?
  1500. Let's write another one, but this time it will return
  1501. an implementation of <code>image.Image</code> instead of a slice of data.
  1502. <p>
  1503. Define your own <code>Image</code> type, implement
  1504. <a target="_blank" href="http://golang.org/pkg/image/#Image" target="_blank">the necessary methods</a>,
  1505. and call <code>pic.ShowImage</code>.
  1506. <p>
  1507. <code>Bounds</code> should return a <code>image.Rectangle</code>, like
  1508. <code>image.Rect(0, 0, w, h)</code>.
  1509. <p>
  1510. <code>ColorModel</code> should return <code>image.RGBAColorModel</code>.
  1511. <p>
  1512. <code>At</code> should return a color;
  1513. the value <code>v</code> in the last picture generator corresponds to
  1514. <code>image.RGBAColor{v, v, 255, 255}</code> in this one.
  1515. <div>
  1516. package main
  1517. import (
  1518. "image"
  1519. "<span class="appengineMode">tour</span><span class="localMode">go-tour.googlecode.com/hg</span>/pic"
  1520. )
  1521. type Image struct{}
  1522. func main() {
  1523. m := Image{}
  1524. pic.ShowImage(m)
  1525. }
  1526. </div>
  1527. </div>
  1528. <div class="slide">
  1529. <h2>Exercise: Rot13 Reader</h2>
  1530. <p>
  1531. A common pattern is an
  1532. <a target="_blank" href="http://golang.org/pkg/io/#Reader">io.Reader</a> that wraps
  1533. another <code>io.Reader</code>, modifying the stream in some way.
  1534. <p>
  1535. For example, the
  1536. <a target="_blank" href="http://golang.org/pkg/compress/gzip/#Decompressor.NewReader">gzip.NewReader</a>
  1537. function takes an <code>io.Reader</code> (a stream of gzipped data)
  1538. and returns a <code>*gzip.Decompressor</code> that also implements
  1539. <code>io.Reader</code> (a stream of the decompressed data).
  1540. <p>
  1541. Implement a <code>rot13Reader</code> that implements
  1542. <code>io.Reader</code> and reads from an <code>io.Reader</code>,
  1543. modifying the stream by applying the
  1544. <a target="_blank" href="http://en.wikipedia.org/wiki/ROT13">ROT13</a>
  1545. substitution cipher to all alphabetical characters.
  1546. <p>
  1547. The <code>rot13Reader</code> type is provided for you. Make it an
  1548. <code>io.Reader</code> by implementing its <code>Read</code> method.
  1549. <div>
  1550. package main
  1551. import (
  1552. "io"
  1553. "os"
  1554. "strings"
  1555. )
  1556. type rot13Reader struct {
  1557. r io.Reader
  1558. }
  1559. func main() {
  1560. s := strings.NewReader(
  1561. "Lbh penpxrq gur pbqr!")
  1562. r := rot13Reader{s}
  1563. io.Copy(os.Stdout, &r)
  1564. }
  1565. </div>
  1566. </div>
  1567. <div class="toc">Concurrency</div>
  1568. <div class="slide nocode">
  1569. <h2>Concurrency</h2>
  1570. </div>
  1571. <div class="slide">
  1572. <h2>Goroutines</h2>
  1573. <p>
  1574. A <i>goroutine</i> is a lightweight thread managed by the Go runtime.
  1575. <pre>go f(x, y, z)</pre>
  1576. <p>
  1577. starts a new goroutine running
  1578. <pre>f(x, y, z)</pre>
  1579. <p>
  1580. The evaluation
  1581. of <code>f</code>, <code>x</code>, <code>y</code>, and <code>z</code>
  1582. happens in the current goroutine and the execution of <code>f</code>
  1583. happens in the new goroutine.
  1584. <p>
  1585. Goroutines run in the same address space, so access to shared memory
  1586. must be synchronized. The <code><a href="http://golang.org/pkg/sync/"
  1587. target="_blank">sync</a></code> package provides useful primitives,
  1588. although you won't need them much in Go as there are other primitives.
  1589. (See the next slide.)
  1590. <div>
  1591. package main
  1592. import (
  1593. "fmt"
  1594. "<span class="appengineMode">runtime</span><span class="localMode">time</span>"
  1595. )
  1596. func say(s string) {
  1597. for i := 0; i < 5; i++ {
  1598. <span class="appengineMode">runtime.Gosched()</span><span class="localMode">time.Sleep(100e6)</span>
  1599. fmt.Println(s)
  1600. }
  1601. }
  1602. func main() {
  1603. go say("world")
  1604. say("hello")
  1605. }
  1606. </div>
  1607. </div>
  1608. <div class="slide">
  1609. <h2>Channels</h2>
  1610. <p>
  1611. Channels are a typed conduit through which you can send and receive values with the channel operator, <code>&lt;-</code>.
  1612. <pre>
  1613. ch <- v // Send v to channel ch.
  1614. v := <-ch // Receive from ch, and
  1615. // assign value to v.
  1616. </pre>
  1617. <p>
  1618. (The data flows in the direction of the "arrow".)
  1619. <p>
  1620. Like maps and slices, channels must be created before use:
  1621. <pre>
  1622. ch := make(chan int)
  1623. </pre>
  1624. <p>
  1625. By default, sends and receives block until the other side is ready.
  1626. This allows goroutines to synchronize without explicit locks or
  1627. condition variables.
  1628. <div>
  1629. package main
  1630. import "fmt"
  1631. func sum(a []int, c chan int) {
  1632. sum := 0
  1633. for _, v := range a {
  1634. sum += v
  1635. }
  1636. c <- sum // send sum to c
  1637. }
  1638. func main() {
  1639. a := []int{7, 2, 8, -9, 4, 0}
  1640. c := make(chan int)
  1641. go sum(a[:len(a)/2], c)
  1642. go sum(a[len(a)/2:], c)
  1643. x, y := <-c, <-c // receive from c
  1644. fmt.Println(x, y, x + y)
  1645. }
  1646. </div>
  1647. </div>
  1648. <div class="slide">
  1649. <h2>Buffered Channels</h2>
  1650. <p>
  1651. Channels can be <i>buffered</i>. Provide the buffer length as the
  1652. second argument to <code>make</code> to initialize a buffered channel:
  1653. <pre>
  1654. ch := make(chan int, 100)
  1655. </pre>
  1656. <p>
  1657. Sends to a buffered channel block only when the buffer is full.
  1658. Receives block when the buffer is empty.
  1659. <p>
  1660. Modify the example to overfill the buffer and see what happens.
  1661. <div>
  1662. package main
  1663. import "fmt"
  1664. func main() {
  1665. c := make(chan int, 2)
  1666. c <- 1
  1667. c <- 2
  1668. fmt.Println(<-c)
  1669. fmt.Println(<-c)
  1670. }
  1671. </div>
  1672. </div>
  1673. <div class="slide">
  1674. <h2>Range and Close</h2>
  1675. <p>
  1676. A sender can <code>close</code> a channel to indicate that no more
  1677. values will be sent. Receivers can test whether a channel has been
  1678. closed by assigning a second parameter to the receive expression: after
  1679. <pre>
  1680. v, ok := &lt;-ch</pre>
  1681. <p>
  1682. <code>ok</code> is <code>false</code> if there are no more values to
  1683. receive and the channel is closed.
  1684. <p>
  1685. The loop <code>for i := range c</code> receives values from the
  1686. channel repeatedly until it is closed.
  1687. <p>
  1688. <b>Note:</b> Only the sender should close a channel, never the
  1689. receiver. Sending on a closed channel will cause a panic.
  1690. <p>
  1691. <b>Another note</b>: Channels aren't like files; you don't usually
  1692. need to close them. Closing is only necessary when the receiver must be
  1693. told there are no more values coming.
  1694. <div>
  1695. package main
  1696. import (
  1697. "fmt"
  1698. )
  1699. func fibonacci(n int, c chan int) {
  1700. x, y := 1, 1
  1701. for i := 0; i < n; i++ {
  1702. c <- x
  1703. x, y = y, x + y
  1704. }
  1705. close(c)
  1706. }
  1707. func main() {
  1708. c := make(chan int, 10)
  1709. go fibonacci(cap(c), c)
  1710. for i := range c {
  1711. fmt.Println(i)
  1712. }
  1713. }
  1714. </div>
  1715. </div>
  1716. <div class="slide">
  1717. <h2>Select</h2>
  1718. <p>
  1719. The <code>select</code> statement lets a goroutine wait on multiple
  1720. communication operations.
  1721. <p>
  1722. A <code>select</code> blocks until one of its cases can run, then it
  1723. executes that case. It chooses one at random if multiple are ready.
  1724. <div>
  1725. package main
  1726. import "fmt"
  1727. func fibonacci(c, quit chan int) {
  1728. x, y := 1, 1
  1729. for {
  1730. select {
  1731. case c <- x:
  1732. x, y = y, x + y
  1733. case <-quit:
  1734. fmt.Println("quit")
  1735. return
  1736. }
  1737. }
  1738. }
  1739. func main() {
  1740. c := make(chan int)
  1741. quit := make(chan int)
  1742. go func() {
  1743. for i := 0; i < 10; i++ {
  1744. fmt.Println(<-c)
  1745. }
  1746. quit <- 0
  1747. }()
  1748. fibonacci(c, quit)
  1749. }
  1750. </div>
  1751. </div>
  1752. <div class="slide">
  1753. <h2>Default Selection</h2>
  1754. <p>
  1755. The <code>default</code> case in a <code>select</code> is run if no
  1756. other case is ready.
  1757. <p>
  1758. Use a <code>default</code> case to try a send or receive without
  1759. blocking:
  1760. <pre>
  1761. select {
  1762. case i := <-c:
  1763. // use i
  1764. default:
  1765. // receiving from c would block
  1766. }</pre>
  1767. <p>
  1768. <span class="appengineMode">
  1769. <b>Note:</b> This example won't run through the web-based tour user
  1770. interface because the
  1771. <a target="_blank" href="http://golang.org/doc/play/">sandbox
  1772. environment</a> has no concept of time. You may want to
  1773. <a target="_blank" href="http://golang.org/doc/install.html">install
  1774. Go</a> to see this example in action.
  1775. </span>
  1776. <div>
  1777. package main
  1778. import (
  1779. "fmt"
  1780. "time"
  1781. )
  1782. func main() {
  1783. tick := time.Tick(1e8)
  1784. boom := time.After(5e8)
  1785. for {
  1786. select {
  1787. case <-tick:
  1788. fmt.Println("tick.")
  1789. case <-boom:
  1790. fmt.Println("BOOM!")
  1791. return
  1792. default:
  1793. fmt.Println(" .")
  1794. time.Sleep(5e7)
  1795. }
  1796. }
  1797. }
  1798. </div>
  1799. </div>
  1800. <div class="slide nocode">
  1801. <h2>Exercise: Equivalent Binary Trees</h2>
  1802. <p>
  1803. There can be many different binary trees with the same sequence of
  1804. values stored at the leaves.
  1805. For example, here are two binary trees storing the sequence
  1806. 1, 1, 2, 3, 5, 8, 13.
  1807. <img src="static/fig4.png">
  1808. <p>
  1809. A function to check whether two binary trees store the same sequence is
  1810. quite complex in most languages. We'll use Go's concurrency and
  1811. channels to write a simple solution.
  1812. <p>
  1813. This example uses the <code>tree</code> package, which defines the type:
  1814. <pre>
  1815. type Tree struct {
  1816. Left *Tree
  1817. Value int
  1818. Right *Tree
  1819. }
  1820. </pre>
  1821. </div>
  1822. <div class="slide">
  1823. <h2>Exercise: Equivalent Binary Trees</h2>
  1824. <p>
  1825. <b>1.</b> Implement the <code>Walk</code> function.
  1826. <p>
  1827. <b>2.</b> Test the <code>Walk</code> function.
  1828. <p>
  1829. The function <code>tree.New(k)</code> constructs a randomly-structured
  1830. binary tree holding the values <code>k</code>, <code>2k</code>, <code>3k</code>, ...,
  1831. <code>10k</code>.
  1832. <p>
  1833. Create a new channel <code>ch</code> and kick off the walker:
  1834. <pre>
  1835. go Walk(tree.New(1), ch)
  1836. </pre>
  1837. <p>
  1838. Then read and print 10 values from the channel.
  1839. It should be the numbers 1, 2, 3, ..., 10.
  1840. <p>
  1841. <b>3.</b> Implement the <code>Same</code> function using <code>Walk</code>
  1842. to determine whether <code>t1</code> and <code>t2</code> store the same values.
  1843. <p>
  1844. <b>4.</b> Test the <code>Same</code> function.
  1845. <p>
  1846. <code>Same(tree.New(1), tree.New(1))</code> should return true, and
  1847. <code>Same(tree.New(1), tree.New(2))</code> should return false.
  1848. <div>
  1849. package main
  1850. import "<span class="appengineMode">tour</span><span class="localMode">go-tour.googlecode.com/hg</span>/tree"
  1851. // Walk walks the tree t sending all values
  1852. // from the tree to the channel ch.
  1853. func Walk(t *tree.Tree, ch chan int)
  1854. // Same determines whether the trees
  1855. // t1 and t2 contain the same values.
  1856. func Same(t1, t2 *tree.Tree) bool
  1857. func main() {
  1858. }
  1859. </div>
  1860. </div>
  1861. <div class="slide">
  1862. <h2>Exercise: Web Crawler</h2>
  1863. <p>
  1864. In this exercise you'll use Go's concurrency features to
  1865. parallelize a web crawler.
  1866. <p>
  1867. Modify the <code>Crawl</code> function to fetch URLs in parallel
  1868. without fetching the same URL twice.
  1869. <div>
  1870. package main
  1871. import (
  1872. "os"
  1873. "fmt"
  1874. )
  1875. type Fetcher interface {
  1876. // Fetch returns the body of URL and
  1877. // a slice of URLs found on that page.
  1878. Fetch(url string) (body string, urls []string, err os.Error)
  1879. }
  1880. // Crawl uses fetcher to recursively crawl
  1881. // pages starting with url, to a maximum of depth.
  1882. func Crawl(url string, depth int, fetcher Fetcher) {
  1883. // TODO: Fetch URLs in parallel.
  1884. // TODO: Don't fetch the same URL twice.
  1885. // This implementation doesn't do either:
  1886. if depth <= 0 {
  1887. return
  1888. }
  1889. body, urls, err := fetcher.Fetch(url)
  1890. if err != nil {
  1891. fmt.Println(err)
  1892. return
  1893. }
  1894. fmt.Printf("found: %s %q\n", url, body)
  1895. for _, u := range urls {
  1896. Crawl(u, depth-1, fetcher)
  1897. }
  1898. return
  1899. }
  1900. func main() {
  1901. Crawl("http://golang.org/", 4, fetcher)
  1902. }
  1903. // fakeFetcher is Fetcher that returns canned results.
  1904. type fakeFetcher map[string]*fakeResult
  1905. type fakeResult struct {
  1906. body string
  1907. urls []string
  1908. }
  1909. func (f *fakeFetcher) Fetch(url string) (string, []string, os.Error) {
  1910. if res, ok := (*f)[url]; ok {
  1911. return res.body, res.urls, nil
  1912. }
  1913. return "", nil, fmt.Errorf("not found: %s", url)
  1914. }
  1915. // fetcher is a populated fakeFetcher.
  1916. var fetcher = &fakeFetcher{
  1917. "http://golang.org/": &fakeResult{
  1918. "The Go Programming Language",
  1919. []string{
  1920. "http://golang.org/pkg/",
  1921. "http://golang.org/cmd/",
  1922. },
  1923. },
  1924. "http://golang.org/pkg/": &fakeResult{
  1925. "Packages",
  1926. []string{
  1927. "http://golang.org/",
  1928. "http://golang.org/cmd/",
  1929. "http://golang.org/pkg/fmt/",
  1930. "http://golang.org/pkg/os/",
  1931. },
  1932. },
  1933. "http://golang.org/pkg/fmt/": &fakeResult{
  1934. "Package fmt",
  1935. []string{
  1936. "http://golang.org/",
  1937. "http://golang.org/pkg/",
  1938. },
  1939. },
  1940. "http://golang.org/pkg/os/": &fakeResult{
  1941. "Package os",
  1942. []string{
  1943. "http://golang.org/",
  1944. "http://golang.org/pkg/",
  1945. },
  1946. },
  1947. }
  1948. </div>
  1949. </div>
  1950. <div class="slide nocode">
  1951. <h2>Where to Go from here...</h2>
  1952. <p class="appengineMode">
  1953. You can get started by
  1954. <a href="http://golang.org/doc/install.html">installing Go</a> or
  1955. downloading the
  1956. <a href="http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Go">Go App Engine SDK</a>.
  1957. </p>
  1958. <p>
  1959. <span class="appengineMode">Once you have Go on your machine, the</span>
  1960. <span class="localMode">The</span>
  1961. <a target="_blank" href="http://golang.org/doc/docs.html">Go Documentation</a>
  1962. is a great place to
  1963. <span class="appengineMode">continue</span>
  1964. <span class="localMode">start</span>.
  1965. It contains references, tutorials, videos, and more.
  1966. <p>
  1967. If you need help with the standard library,
  1968. see the <a target="_blank" href="http://golang.org/pkg/">package
  1969. reference</a>. For help with the language itself, you might be
  1970. surprised to find the
  1971. <a target="_blank" href="http://golang.org/doc/go_spec.html">Language
  1972. Spec</a> is quite readable.
  1973. <p>
  1974. If you're interested in writing web applications,
  1975. see the
  1976. <a target="_blank" href="http://golang.org/doc/codelab/wiki/">Wiki
  1977. Codelab</a>.
  1978. <p>
  1979. If you want to further explore Go's concurrency model, see the
  1980. <a target="_blank" href="http://golang.org/doc/codewalk/sharemem/">Share Memory by Communicating</a>
  1981. codewalk.
  1982. <p>
  1983. The <a target="_blank" href="http://golang.org/doc/codewalk/functions/">First Class Functions in Go</a>
  1984. codewalk gives an interesting perspective on Go's function types.
  1985. <p>
  1986. The <a target="_blank" href="http://blog.golang.org/">Go Blog</a> has a
  1987. large archive of informative Go articles.
  1988. <p>
  1989. Visit <a target="_blank" href="http://golang.org">golang.org</a> for
  1990. more.
  1991. </div>
  1992. </div><!-- end slides -->
  1993. </body>
  1994. </html>