go-tutorial Documentation Release latest

Similar documents
William Kennedy. Brian Ketelsen Erik St. Martin Steve Francia FOREWORD BY MANNING WITH

Homework 5: Spatial Games : Programming for Scientists Due: Thursday, March 3, 2016 at 11:59 PM

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

Go Tutorial. Arjun Roy CSE 223B, Spring 2017

Introduzione a Go e RPC in Go

Homework 6: Spatial Games Due: 11:59pm on Friday, October 30

Chapter Two. Lesson A. Objectives. Exploring the UNIX File System and File Security. Understanding Files and Directories

CSC209. Software Tools and Systems Programming.

The Go Programming Language. Frank Roberts

Assignment 1: Communicating with Programs

Processes in linux. What s s a process? process? A dynamically executing instance of a program. David Morgan. David Morgan

How to program with Matlab (PART 1/3)

5/20/2007. Touring Essential Programs

This document describes version 2.07 of File::Path, released

Go in Action: Benchmarking

DAB/MOT Data Carousel Support Library Linux Server Implementation

Overview of the UNIX File System

Don t Go Java! Edition 2019

Formal languages and computation models

CSC209. Software Tools and Systems Programming.

GRACES Data Reduction Cookbook

RPC and Threads. Jinyang Li. These slides are based on lecture notes of 6.824

Filesystem Hierarchy and Permissions

System Administration for Beginners

EECS 470 Lab 5. Linux Shell Scripting. Friday, 1 st February, 2018

Essential Unix and Linux! Perl for Bioinformatics, ! F. Pineda

Overview of the UNIX File System. Navigating and Viewing Directories

CVS. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 21

C Programming. A quick introduction for embedded systems. Dr. Alun Moon UNN/CEIS. September 2008

INSTITUTE OF AERONAUTICAL ENGINEERING

Jackson State University Department of Computer Science CSC / Advanced Information Security Spring 2013 Lab Project # 5

UNIX Tutorial One

Go for Java Developers

Access Permissions. Agenda. chmod Command (Relative Method) File / Directory Permissions

Patterns for polymorphic operations

EAPI Cheat Sheet. Version th November Abstract

Introduction of Linux

Computers and Computation. The Modern Computer. The Operating System. The Operating System

JEE2600 INTRODUCTION TO DIGITAL LOGIC AND COMPUTER DESIGN. ModelSim Tutorial. Prepared by: Phil Beck 9/8/2008. Voter Function

PYTHON. BBM103 Introduction to Programming Lab 1. Hacettepe University Computer Engineering Department

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

File System. Preview. File Name. File Structure. File Types. File Structure. Three essential requirements for long term information storage

Lecture #2: Programming Structures: Loops and Functions

Filesystem Hierarchy and Permissions

TIBCO FTL R Programming Tutorial Software Release 5.3 October 2017

Linux desktop app guide Documentation. Thomas Kluyver & contributors

Using WestGrid from the desktop Oct on Access Grid

Operating Systems. Copyleft 2005, Binnur Kurt

Operating Systems 3. Operating Systems. Content. What is an Operating System? What is an Operating System? Resource Abstraction and Sharing

Go Tutorial. To do. A brief, gentle intro to Go. Next Networking. q Today

We do not teach programming

Matt Butcher Matt Farina

If Statements, For Loops, Functions


LAE 5.1. Release Notes. Version 1.0

Project 3: Base64 Content-Transfer-Encoding

Getting Started with Apache NiFi Registry

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND

Kindle Books The C Programming Language

About Tutorial. Audience. Prerequisites. Disclaimer & Copyright. Euphoria

Extra Notes - Data Stores & APIs - using MongoDB and native driver

Successful Go program design. Six years on

Introduction to Programming Style

First steps on Linux and programming

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Creating a new CDC policy using the Database Administration Console

Preview. COSC350 System Software, Fall

A shell can be used in one of two ways:

This document describes version 2.09 of File::Path, released

Processes. What s s a process? process? A dynamically executing instance of a program. David Morgan

FX SERIES. Programmer s Guide. Embedded SDK. MN000540A01 Rev. A

Advanced Unix Programming Module 03 Raju Alluri spurthi.com

Installation and Upgrade Guide Zend Studio 9.x

LAE Release Notes. Version 1.0

Segmentation with Paging. Review. Segmentation with Page (MULTICS) Segmentation with Page (MULTICS) Segmentation with Page (MULTICS)

Motivations History Principles Language Gommunity Success stories Conclusion. Let s Go! A brief introduction to Google s new language.

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

Introduction to Programming with Python 3, Ami Gates. Chapter 1: Creating a Programming Environment

Lab #12: Shell Scripting

Installation and Upgrade Guide Zend Studio 9.x

416 Distributed Systems. RPC Day 2 Jan 12, 2018

Effective TCP/IP Programming: 44 Tips To Improve Your Network Programs: 44 Tips To Improve Your Network Programs Ebooks Free

COURSE INTRODUCTION. Software Tools EECS2031 Winter 2018 Manos Papagelis. Thanks to Karen Reid and Alan J Rosenthal for material in these slides

WebDocs 6.5. New Features and Functionality. An overview of the new features that increase functionality and ease of use including:

WRITING CONSOLE APPLICATIONS IN C

Adobe Illustrator CS3 Classroom In A Book (Book & CD-ROM) Ebooks Free

PUG (Prover of User GPU Programs) v0.2

(Refer Slide Time: 1:26)

Portions adapted from A Visual Guide to Version Control. Introduction to CVS

Exercise sheet 1 To be corrected in tutorials in the week from 23/10/2017 to 27/10/2017

CPSC : Program 3, Perceptron and Backpropagation

Applied Informatics POCO PRO C++ Frameworks

CS 300. Data Structures

Lecture 3: Web Servers / PHP and Apache. CS 383 Web Development II Monday, January 29, 2018

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

Chapter 2 Working with Data Types and Operators

COMP s1 Lecture 1

Your First Ruby Script

Project C: B+Tree. This project may be done in groups of up to three people.

Transcription:

go-tutorial Documentation Release latest Jun 04, 2017

Contents 1 Lesson 1: Introduction, installation and first code 3 1.1 Introduction............................................... 3 1.2 Links, bibliography............................................ 3 1.3 Installation................................................ 4 1.4 First code................................................. 4 1.4.1 Project.............................................. 4 1.4.2 Solution 1............................................ 5 1.4.3 Solution 2............................................ 7 1.4.4 Solution 3............................................ 9 1.5 Whetting you appetite.......................................... 10 i

ii

Contents: This tutorial approach to the Go programming language is higly personal: it handles the questions I ask myself when I study a new programming language. It works for me, let us hope it works for you as well. The emphasis is not so much on syntax but on answering questions, big and small, which cross my mind when I am learning and - when left unanswered - prevent me to work well with the language. Contents 1

2 Contents

CHAPTER 1 Lesson 1: Introduction, installation and first code Introduction This tutorial approach to the Go programming language is higly personal: it handles the questions I ask myself when I study a new programming language. It works for me, let us hope it works for you as well. The emphasis is not so much on syntax but on answering questions, big and small, which cross my mind when I am learning and - when left unanswered - prevent me to work well with the language. Why should you learn Go? Strangely enough, a tutorial, pretending to be big on answering questions, does not answer the very first one. I think, if you want to spend your time on learning a new language, you are likely to know the answer already. Moreover, as a side-effect of going through this tutorial, you will certainly note the ease with which Go handles concurrency, the quality of the tool set and the backwards compatibility of the language. This tutorial assumes you are already familiar with a programming language. Knowledge of Python would be a good basis to start this tutorial but others work as well. Note: I do not think that Go is a replacement of Python: changing Python for Go is like replacing a commuter s bicycle with a racing bicycle: only in particular circumstances a good idea! Links, bibliography The Go Programming Language Install the Go tools Effective Go The Go Programming Language Specification Package Documentation 3

Go in Action / William Kennedy with Brian Ketelsen and Erik St. Martin, Foreword by Steve Francia, November 2015 - ISBN 9781617291784-264 pages Programming in Go: Creating Applications for the 21st Century / Mark Summerfield - Published May 4, 2012 by Addison-Wesley Professional - ISBN 0-321-77463-9 Go Programming Language, The / Alan A. A. Donovan, Brian W. Kernighan - Published Nov 16, 2015 by Addison-Wesley Professional - ISBN 0-13-419058-0 Installation The Go Programming Language This tutorial handles Go 1.8+ Go is a pragmatic language: it tries to circumvent all kinds of essentially meaningless discussions (e.g. Where to place { and } in the code). Warning: Make the distinction between the Go specification and the workings of the Go tools which are installed on your computer. Working with the standard Go tools comes with a price: you develop your source code according to the way the Go designers intended it: you organise the code in a workspace. This workspace presents itself as a directory in your home directory with a standard name go. This directory contains the sub-directories: src: contains the source code bin: contains the generated binaries pkg: contains the compiled libraries Make sure that the directory containing the go binary is in your PATH Then: go env Note the value associated with GOPATH and make a subdirectory bin in that directory. Put this new directory also in your PATH Later we will come back to these directories and environment variables. First code Project The environment variable BROCADE_REGISTRY holds the name of a JSON file containing a simple key/value store. These are properties to use in your software: instead of hard-coding a value, we use a key (consisting of lowercase ASCII, digits and a MINUS symbol) that we associate with an actual value. In this project we will build a simple go based software which can query this key/value store. 4 Chapter 1. Lesson 1: Introduction, installation and first code

Solution 1 In the subdirectory src of GOPATH, make a directory brocade.be, and here a sub-directory rphilips (user your own userid). Finally, another directory delphi1 In this directory, create a file delphi1.go: 1 package main 2 3 import ( 4 "bufio" 5 "os" 6 "log" 7 "fmt" 8 "io/ioutil" 9 "encoding/json" 10 "strings" 11 ) 12 13 var registry map[string]string 14 15 16 func loadregistry() { 17 // retrieve location from environment variabel 18 registryfile := os.getenv("brocade_registry") 19 if registryfile == "" { 20 log.fatal("brocade_registry environment variable is not defined") 21 } 22 23 // read file 24 b, err := ioutil.readfile(registryfile) 25 if err!= nil { 26 log.fatal(fmt.sprintf("cannot read file '%s' (BROCADE_REGISTRY environment variable)\n", registryfile), err) 27 } 28 29 // interpret JSON 30 err = json.unmarshal(b, &registry) 31 if err!= nil { 32 log.fatal(fmt.sprintf("registry file '%s' does not contain valid JSON.\nUse http://jsonlint.com/\n", registryfile), err) 33 } 34 } 35 36 37 func main() { 38 39 // load registry 40 loadregistry() 41 42 reader := bufio.newreader(os.stdin) 43 44 // loop and read until empty 45 for { 46 fmt.print("enter key: ") 47 key, err := reader.readstring('\n') 48 if err!= nil { 1.4. First code 5

49 log.fatal("cannot read from stdin") 50 } 51 key = strings.trimspace(key) 52 if key == "" { 53 break 54 } 55 value, ok := registry[key] 56 if!ok { 57 value = "?" 58 } 59 fmt.printf("%s -> %s\n\n", key, value) 60 } 61 62 } Changing to the directory with delphi1.go go build go install try it: delphi1 Notes Line 1: Every Go file contains a package statement. The main package is used for executables Line 3: Import statement. The corresponding packages can be referenced by the last part of the impart string Line 13: Go is statically typed and compiled, so the type of every value has to be known at compile time. In Go, evry variable is initialised, even it is silent. Line 16: the basic structuring component is the function. Line 18: note how a name is referenced Line 24: Functions can return multiple values, the receiving and of the application has to capture as many values as are returned Line 30: Go can work with pointers without the drawback of the C language Line 37: package main needs a func main() Line 45: elegant and powerful way to code an infinite loop Some experiments insert a superfluous import and compile 1 import ( 2 "bufio" 3 "os" 4 "log" 5 "fmt" 6 "crypto/aes" 7 "io/ioutil" 8 "encoding/json" 6 Chapter 1. Lesson 1: Introduction, installation and first code

9 "strings" 10 ) remove package main remove func main() Solution 2 The previous solution does not allow for re-use: every application which needs the registry has to implement its own loadregistry() So, let us create a new directory: src/brocade.be/rphilips/registry and put a file registry.go: 1 package registry 2 3 import ( 4 "os" 5 "log" 6 "fmt" 7 "io/ioutil" 8 "encoding/json" 9 ) 10 11 var Registry = loadregistry() 12 13 func loadregistry() (registry map[string]string) { 14 15 16 // retrieve location from environment variabel 17 registryfile := os.getenv("brocade_registry") 18 if registryfile == "" { 19 log.fatal("brocade_registry environment variable is not defined") 20 } 21 22 // read file 23 b, err := ioutil.readfile(registryfile) 24 if err!= nil { 25 log.fatal(fmt.sprintf("cannot read file '%s' (BROCADE_REGISTRY environment variable)\n", registryfile), err) 26 } 27 28 // interpret JSON 29 err = json.unmarshal(b, &registry) 30 if err!= nil { 31 log.fatal(fmt.sprintf("registry file '%s' does not contain valid JSON.\nUse http://jsonlint.com/\n", registryfile), err) 32 } 33 34 return 35 } Changing to the directory with registry.go go build go install 1.4. First code 7

Notes Line 1: the first line is the required package statement. The name of a registry is alsways an identifier and, by convention, lowercase Line 11: a name of a variable is intoduced here. Line 13: func loadregistry is defined with a named return value Line 34: the naked return, returns registry Some experiments remove package registry note the naked return Finally, let us create a directory: src/brocade.be/rphilips/delphi2 and put a file delphi2.go: 1 package main 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "log" 8 "strings" 9 10 "brocade.be/rphilips/registry" 11 ) 12 13 func main() { 14 15 reader := bufio.newreader(os.stdin) 16 17 for { 18 fmt.print("enter key: ") 19 key, err := reader.readstring('\n') 20 if err!= nil { 21 log.fatal("cannot read from stdin") 22 break; 23 } 24 key = strings.trimspace(key) 25 if key == "" { 26 break 27 } 28 value, ok := registry.registry[key] 29 if!ok { 30 value = "?" 31 } 32 fmt.printf("%s -> %s\n\n", key, value) 33 } 34 } Changing to the directory with delphi2.go go build go install 8 Chapter 1. Lesson 1: Introduction, installation and first code

try it: delphi2 Notes Line 10: the brocade.be/rphilips/registry library is imported. The name registry and all its exported items (those starting with an uppercase) are available to our program Line 28: the registry.registry is used Some experiments change in registry.go: var Registry map[string]string to var registry map[string]string and compile Solution 3 We can optimize this solution. Change registry.go to: 1 package registry 2 3 import ( 4 "os" 5 "log" 6 "fmt" 7 "io/ioutil" 8 "encoding/json" 9 ) 10 11 var Registry map[string]string 12 13 14 func init() { 15 registryfile := os.getenv("brocade_registry") 16 if registryfile == "" { 17 log.fatal("brocade_registry environment variable is not defined") 18 } 19 b, err := ioutil.readfile(registryfile) 20 if err!= nil { 21 log.fatal(fmt.sprintf("cannot read file '%s' (BROCADE_REGISTRY environment variable)\n", registryfile), err) 22 } 23 err = json.unmarshal(b, &Registry) 24 if err!= nil { 25 log.fatal(fmt.sprintf("registry file '%s' does not contain valid JSON.\nUse http://jsonlint.com/\n", registryfile), err) 26 } 27 28 } Changing to the directory with registry.go 1.4. First code 9

go build go install Changing to the directory with delphi2.go go build go install Changing to the directory with registry.go go build go install try it: delphi2 Notes Line 14: the func init() library is imported. There can be several of those func init() in a package (even in the same file). These functions have no arguments and no return values. But they are executed the moment their package is imported. Some experiments in registry.go, var Registry map[string]string after init(){...} in registry.go, put a second init(){...} after init(){...} Whetting you appetite Changing to the directory with delphi2.go, chose your poison: For MS-Windows: GOOS=windows GOARCH=amd64 go build For OSX: GOOS=darwin GOARCH=amd64 go build For linux: GOOS=linux GOARCH=amd64 go build and transfer the binary to an appropriate machine. Is this a UNIX machine, do not forget to set the execution permission: chmod +x delphi2 and try it: 10 Chapter 1. Lesson 1: Introduction, installation and first code

delphi2 1.5. Whetting you appetite 11

12 Chapter 1. Lesson 1: Introduction, installation and first code

Index B BROCADE_REGISTRY, 4 E environment variable BROCADE_REGISTRY, 4 GOPATH, 4, 5 PATH, 4 G GOPATH, 4, 5 P PATH, 4 13