0% found this document useful (0 votes)
35 views

Lecture 05-Introduction To Golang

Uploaded by

kausar naznin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Lecture 05-Introduction To Golang

Uploaded by

kausar naznin
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 93

Lecture 05 - Introduction to Golang

Introduction to Golang

1
Lecture 05 - Introduction to Golang

• Go is an open source
programming language that
makes it easy to build simple,
reliable, and efficient software.

2
Lecture 05 - Introduction to Golang

Why should we learn a new


Language?
• Go is expressive, concise, clean, and
efficient – says a lot !!

• Go is easy and fun 

• Just play along and you’ll find out

3
Lecture 05 - Introduction to Golang

Go at Google
• Go is a programming language designed by Google to
help solve Google's problems, and Google has big
problems
• The hardware is big and the software is big.
– many millions of lines of software, with servers mostly in C++
and lots of Java and Python for the other pieces.
– Thousands of engineers work on the code, at the "head" of a
single tree comprising all the software,
– From day to day there are significant changes to all levels of the
tree.
– A large custom-designed distributed build system makes
development at this scale feasible, but it's still big.

4
Lecture 05 - Introduction to Golang

Go at Google
• And of course, all this software runs on zillions of
machines, which are treated as a modest number of
independent, networked compute clusters.

5
Lecture 05 - Introduction to Golang

Pain points
• Slow builds
• Uncontrolled dependencies
• Each programmer using a different subset of the
language
• Poor program understanding (code hard to read, poorly
documented, and so on)
• Duplication of effort
• Cost of updates
• Difficulty of writing automatic tools
• ….

6
Lecture 05 - Introduction to Golang

Header files in C++

7
Lecture 05 - Introduction to Golang

Header files in C++

8
Lecture 05 - Introduction to Golang

Header files in C++

9
Lecture 05 - Introduction to Golang

Header files in C++

10
Lecture 05 - Introduction to Golang

Header files in C++


• Header files consist of two parts.
– The first part is called a header guard
– The second part is the actual content of the .h
file

11
Lecture 05 - Introduction to Golang

Header files in C++

12
Lecture 05 - Introduction to Golang

Dependencies in C and C++


• The #ifdef preprocessor directive allow the preprocessor to check
whether a value has been previously #defined. If so, the code
between the #ifdef and corresponding #endif is compiled. If not, the
code is ignored.

13
Lecture 05 - Introduction to Golang

Dependencies in C and C++


• #ifndef is the opposite of #ifdef, in that it allows you to check
whether a name has NOT been defined yet.

14
Lecture 05 - Introduction to Golang

Dependencies in C and C++


• Header guard, prevent a given header file from being
#included more than once from the same file.

15
Lecture 05 - Introduction to Golang

Nice… but it scales very badly


• In 1984, a compilation of ps.c, the source to the
Unix ps command, was observed to #include
<sys/stat.h> 37 times by the time all the
preprocessing had been done.

• The construction of a single C++ binary at


Google can open and read hundreds of
individual header files tens of thousands of
times.

16
Lecture 05 - Introduction to Golang

Dependencies in C and C++


• In 2007, build engineers at Google instrumented
the compilation of a major Google binary.
– Two thousand files that, when concatenated together,
totaled 4.2 megabytes.
– By the time the #includes had been expanded, over 8
gigabytes were being delivered to the input of the
compiler, a blow-up of 2000 bytes for every C++
source byte.

17
Lecture 05 - Introduction to Golang

Dependencies in C and C++


• That 2007 binary took 45 minutes using a distributed
build system

• When builds are slow, there is time to think. The origin


myth for Go states that it was during one of those 45
minute builds that Go was conceived.

18
Lecture 05 - Introduction to Golang

Dependencies in Go
import "encoding/json"

The first step to making Go scale, dependency-


wise, is that the language defines that unused
dependencies are a compile-time error (not a
warning, an error).

19
Lecture 05 - Introduction to Golang

Dependencies in Go
package A imports package B;
package B imports package C;
package A does not import package C

This means that package A uses C only transitively through


its use of B; that is, no identifiers from C are mentioned in
the source code to A, even if some of the items A is using
from B do mention C

20
Lecture 05 - Introduction to Golang

Dependencies in Go
• To build this program,
– first, C is compiled; dependent packages must be built
before the packages that depend on them.
– Then B is compiled; finally A is compiled, and then the
program can be linked.

• When A is compiled, the compiler reads the object file for


B, not its source code. That object file for B contains all
the type information necessary for the compiler to
execute the import "B" clause in the source code for A.

21
Lecture 05 - Introduction to Golang

Results
• Google measured the compilation of a large
Google program written in Go to see how the
source code fanout compared to the C++
analysis done earlier.
• They found it around fifty times better than C++
(as well as being simpler and hence faster to
process)

• It can be further improved !!

22
Lecture 05 - Introduction to Golang

23
Lecture 05 - Introduction to Golang

Installing Go
• The Go Playground, http://play.golang.org (
https://go.dev/play/ )

• The Go Playground is a web service that runs on


go.dev's servers. The service receives a Go program,
compiles, links, and runs the program inside a sandbox,
then returns the output.

24
Lecture 05 - Introduction to Golang

Installing Go

25
Lecture 05 - Introduction to Golang

https://go.dev/

26
Lecture 05 - Introduction to Golang

Installing Go
• You should however install it locally
– Follow instructions at https://go.dev/doc/install, simple steps and
binaries provided.
– Download and install using the setup
– The GOPATH environment variable should be setup

27
Lecture 05 - Introduction to Golang

Some editors with support for


Go
• SublimeText with GoSublime
• Atom with go-plus

28
Lecture 05 - Introduction to Golang

Hello World !!
package main
import "fmt"

func main() {
fmt.Printf("Hello, world.\n")
}

29
Lecture 05 - Introduction to Golang

A web server !!
package main
import (
"io"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world!")
}

func main() {
http.HandleFunc("/", hello)
http.ListenAndServe(":8000", nil)
}
30
Lecture 05 - Introduction to Golang

Let’s not rush


• Before we can move on, it is better to get
organized.

• Good organization of our code and


directories would do wonders 

31
Lecture 05 - Introduction to Golang

Go and GitHub
• The go tool is designed to work with open
source code maintained in public repositories.

• Although you don't need to publish your code,


the model for how the environment is set up
works the same whether you do or not.

32
Lecture 05 - Introduction to Golang

Workspaces
• Go code must be kept inside a workspace.
• A workspace is a directory hierarchy with three
directories at its root:
– src contains Go source files organized into packages (one
package per directory),
– pkg contains package objects, and
– bin contains executable commands.

• The go tool builds source packages and installs


the resulting binaries to the pkg and bin
directories.
33
Lecture 05 - Introduction to Golang

An example

34
Lecture 05 - Introduction to Golang

Go and Version Control


• If you're using a source control system, now would be a
good time to initialize a repository, add the files, and
commit your first change.

– Why you should be using one?


– Which one to use?

35
Lecture 05 - Introduction to Golang

What is Version Control? (why would I need


it...)
• Files goes through frequent changes, new files coming in and old
ones being deleted.
• If you build any kind of application and need to keep track of
“versions” of the filesystem, you need version control.
• If you need to share coding responsibilities or maintenance of a
codebase with another person, you need version control.

• If you want to look like a pro at managing your code, keep a


consistent history (with ease), and feel comfortable handing it off to
someone else, you need version control.

36
Lecture 05 - Introduction to Golang

Types of Version Control


Systems
• Local only - keeps a local database of changes in your local
machine filesystem.
• Centralized - (Subversion, CVS), require a connection to a central
server and “checkout”
• Distributed - (Git, Mercurial) allow for local systems to be “mirrors” of
the central repo. You don’t need to be connected to the central
server to get work or commits done.

37
Lecture 05 - Introduction to Golang

GitHub

38
Lecture 05 - Introduction to Golang

What Git is and what it does


• small piece of software.
• tracks all your files in it’s database. You have to add and remove files into
this tracking system and commit them.
• a single .git directory at the top of your filesystem “watches” the changes
going on and helps you deal with them at commit time.
• “git status” will tell you what has been added, removed, modified, etc. etc.
• When you make a “commit.” Git records a “snapshot” of changes to your
filesystem and records an index number to it. You also write a brief
message about the commit.
• Commit frequently!

39
Lecture 05 - Introduction to Golang

Where it all happens


• In each local .git folder.
• most activity happens locally. Frequent commits, additions, and
changes.

• When you’re ready to share your code with others in your team, or
want to get it ready for deployment to your servers, you can “push” it
to your "remote"

40
Lecture 05 - Introduction to Golang

A Local Git project has three


areas

Unmodified/modified Staged Committed


Files Files Files
Note: working directory sometimes called the “working tree”, staging area sometimes called the “index”.
41
Lecture 05 - Introduction to Golang

Basic Workflow
Basic Git workflow:

1.Modify files in your working directory.


2.Stage files, adding snapshots of them to your staging area.
3.Do a commit, which takes the files as they are in the staging
area and stores that snapshot permanently to your Git
directory.

•Notes:
– If a particular version of a file is in the git directory, it’s considered committed.
– If it’s modified but has been added to the staging area, it is staged.
– If it was changed since it was checked out but has not been staged, it is modified.

42
Lecture 05 - Introduction to Golang

Aside: So what is github?


• GitHub.com is a site for online storage of Git repositories.
• Many open source projects use it, such as the Linux kernel.

Question: Do I have to use github to use Git?


Answer: No! you can use Git locally for your own purposes

43
Lecture 05 - Introduction to Golang

Aside: So what is github?


• You can get free space for open source projects or you can pay
for private projects.

Student Developer Pack

44
Lecture 05 - Introduction to Golang

Get ready to use Git!


1. Set the name and email for Git to use when you commit:
$ git config --global user.name “Bugs Bunny”
$ git config --global user.email [email protected]

• You can call git config –list to verify these are set.
• These will be set globally for all Git projects you work with.
• You can also set variables on a project-only basis by not using the
--global flag.

45
Lecture 05 - Introduction to Golang

Create a local copy of a repo


2. Two common scenarios: (only do one of these)
a) To clone an already existing repo to your current directory:
$ git clone <url> [local dir name]
This will create a directory named local dir name, containing a working copy of the files
from the repo, and a .git directory (used to hold the staging area and your actual
repo)

b) To create a Git repo in your current directory:


$ git init
This will create a .git directory in your current directory.
Then you can commit files in that directory into the repo:
$ git add file1.java
$ git commit –m “initial project version”

46
Lecture 05 - Introduction to Golang

Git commands
command description
git clone url [dir] copy a git repository so you can add to it
git add files adds file contents to the staging area
git commit records a snapshot of the staging area
git status view the status of your files in the working
directory and staging area
git diff shows diff of what is staged and what is
modified but unstaged
git help [command] get help info about a particular command
git pull fetch from a remote repo and try to merge
into the current branch
git push push your new branches and data to a
remote repository
others: init, reset, branch, checkout, merge, log, tag
47
Lecture 05 - Introduction to Golang

Committing files
• The first time we ask a file to be tracked, and every time before we
commit a file we must add it to the staging area:

$ git add hello.java

• This takes a snapshot of these files at this point in time and adds it to the
staging area.
• To move staged changes into the repo we commit:

$ git commit –m “Fixing bug #22”

Note: These commands are just acting on your local version of repo.
48
Lecture 05 - Introduction to Golang

Status and Diff


• To view the status of your files in the working directory and staging area:
$ git status or
$ git status –s

• To see what is modified but unstaged:


$ git diff

49
Lecture 05 - Introduction to Golang

Viewing logs
To see a log of all changes in your local repo:
• $ git log or
• $ git log --oneline (to show a shorter version)

1677b2d Edited first line of readme


258efa7 Added line to readme
0e52da7 Initial commit
• git log -5 (to show only the 5 most recent updates, etc.)

50
Lecture 05 - Introduction to Golang

Undoing Changes - git


checkout
• Undo changes to a file since last commit
– git checkout -- filename
• Look at previous version of project

51
Lecture 05 - Introduction to Golang

Undoing Changes - git


checkout
• If you liked some particular file in previous
version – you can restore it

52
Lecture 05 - Introduction to Golang

Remote Repositories – Push


and pull
• To push our local repo to the GitHub server we'll
need to add a remote repository.
git remote add origin <remote-repo-url>
git push -u origin master

• Pulling is just as simple


git pull origin master

53
Lecture 05 - Introduction to Golang

A Tour of Go
• We would be following the online tour
– https://tour.golang.org or go tool tour

54
Lecture 05 - Introduction to Golang

Hello World !!
package main
import "fmt"

func main() {
fmt.Printf("Hello, world.\n")
}

55
Lecture 05 - Introduction to Golang

Printing on Console – The fmt


package

56
Lecture 05 - Introduction to Golang

Printing on Console – The fmt


package

57
Lecture 05 - Introduction to Golang

Printing on Console – The fmt


package

58
Lecture 05 - Introduction to Golang

Printing on Console – The fmt


package

59
Lecture 05 - Introduction to Golang

A tour of Go
• Packages/Imports/Exported
names/Functions/Variables/Initializers

60
Lecture 05 - Introduction to Golang

Go Packages and Exported


Names
• Let's write a library and use it from the hello program, greetings.
• $ mkdir $GOPATH/src/github.com/user/greetings
• Create a file named mygreetings.go with following code

//Package greetings shows the greetings


package greetings

//GreetingsString is a global variable


var GreetingsString = "Hello World"

//PrintGreetings is a global function


func PrintGreetings(name string) string {
return GreetingsString + "-" + name
}

61
Lecture 05 - Introduction to Golang

Go Packages and Exported


Names
• Next, modify the hello.go to have the following code:

package main

import (
"fmt"
"github.com/user/greetings"
)

func main() {
fmt.Printf(greetings.PrintGreetings("ad "))
}

62
Lecture 05 - Introduction to Golang

A few words about godoc


• A simple, elegant and highly effective approach to document your
work (my own words!)
• We added some comments with our package
• If we godoc -http=:6060 and navigate to
localhost:6060/pkg/github.com/ehteshamz/greetings, we can see
these comments!!

63
Lecture 05 - Introduction to Golang

Remote repositories
• It is good time to push our package to the GitHub,
• Anyone can then use our wonderful greetings package

• You know how to do this?


– git init/add/commit/push … piece of cake 

64
Lecture 05 - Introduction to Golang

Remote repositories
• Lets delete our local repo and get it from GitHub
• This shows how to use remote repos in the Go
go get github.com/user/greetings

…and we have our package back 

65
Lecture 05 - Introduction to Golang

Remote repositories
• Lets do some image processing …
go get -u github.com/disintegration/imaging
…and we have an image processing library

package main
import (
"github.com/disintegration/imaging"
)

func main() {
img, _ := imaging.Open("01.jpg")
thumb := imaging.Thumbnail(img, 100, 100,
imaging.CatmullRom)
imaging.Save(thumb, "dst.jpg")
}

66
Lecture 05 - Introduction to Golang

Arrays
• Go's arrays are values.
• An array variable denotes the entire array; it is not a
pointer to the first array element (as in C/C++).

• This means that when you assign or pass around an


array value you will make a copy of its contents.

67
Lecture 05 - Introduction to Golang

Passing Arrays
• Go's documentation makes it clear that
arrays are passed by copy.

• How to achieve pass by reference?


– Option A - use pointers, complex and less elegant
– Option B - Use slices

68
Lecture 05 - Introduction to Golang

Slices
• Slices build on arrays to provide great power and
convenience.
• A slice literal is declared just like an array literal, except
you leave out the element count:

letters := []string{"a", "b", "c", "d"}

var s []byte
s = make([]byte, 5, 5)
// s = []byte{0, 0, 0, 0, 0}

69
Lecture 05 - Introduction to Golang

Slicing Slices
b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}

// b[1:4] == []byte{'o', 'l', 'a'}, sharing the same storage as b


// b[:2] == []byte{'g', 'o'}
// b[2:] == []byte{'l', 'a', 'n', 'g'}
// b[:] == b

70
Lecture 05 - Introduction to Golang

Slice Internals
• A slice is a descriptor of an array segment. It consists of a pointer to
the array, the length of the segment, and its capacity (the maximum
length of the segment).

• Our variable s, created earlier by make([]byte, 5), is structured like this:

71
Lecture 05 - Introduction to Golang

Slice Internals - Slicing


s = s[2:4]

72
Lecture 05 - Introduction to Golang

Slice Internals - Slicing


• Slicing does not copy the slice's data.
• It creates a new slice value that points to the original array.

• Therefore, modifying the elements (not the slice itself) of a re-slice


modifies the elements of the original slice

d := []byte{'r', 'o', 'a', 'd'}


e := d[2:]
// e == []byte{'a', 'd'}
e[1] = 'm'
// e == []byte{'a', 'm'}
// d == []byte{'r', 'o', 'a', 'm'}

73
Lecture 05 - Introduction to Golang

Erratum – Go Modules
• The support of go modules was added in
v1.11 but wasn’t enforced for $GOPATH
packages till recent versions.

• Packages are handled differently with the


support and enforcement of go modules.

74
Lecture 05 - Introduction to Golang

GO111MODULE
• If you have made the change as announced on the
classroom, you need to undo. It should be on or empty

• You can check the go environment variables by using the


command shown below:

go env

75
Lecture 05 - Introduction to Golang

Go modules - Introduction
• They serve many purposes
– Dependency management, using multiple
versions of the downloaded packages
– Packages from go get are not cluttered in
$GOPATH/src and go code can be written in
directories other than $GOPATH
–…

76
Lecture 05 - Introduction to Golang

back to the greetings package

//Package greetings shows the greetings


package greetings

//GreetingsString is a global variable


var GreetingsString = "Hello World"

//PrintGreetings is a global function


func PrintGreetings(name string) string {
return GreetingsString + "-" + name
}

77
Lecture 05 - Introduction to Golang

back to the greetings package


• With the go modules its path is not guided
by the directory structure but rather a file
named go.mod

78
Lecture 05 - Introduction to Golang

Getting started
• Go modules are initialized by the go init command
followed up by the path of the module

• This creates a file named go.mod in the same directory.


The contents of the file are shown below, it names the
module and go version needed for this module.

79
Lecture 05 - Introduction to Golang

Version control using git


• We know how to do this, right?

80
Lecture 05 - Introduction to Golang

Git tags
• Using git we can tag our releases (provide versions) and
push on the github.
• We call our first release v0.0.1

81
Lecture 05 - Introduction to Golang

getting and using the greetings


package
• Lets create another directory for the main file that uses
this package and add the appropriate content.
• With the go modules we need to again initialize and the
choice of name is less important, as it is main package.

82
Lecture 05 - Introduction to Golang

getting and using the greetings


package
• We add the following code for invoking the package

package main

import (
"fmt"
"github.com/ehteshamz/greetings"
)

func main() {
fmt.Printf(greetings.PrintGreetings("ez "))
}

83
Lecture 05 - Introduction to Golang

go tools at atom are not happy

84
Lecture 05 - Introduction to Golang

Adding dependency
• We have not added dependency for our main package that it needs
the greeting module.
• This can be done by editing the go.mod file or just running go get in
the same folder
• You can notice that we are adding version info with the package and
how the contents of go.mod change

85
Lecture 05 - Introduction to Golang

Adding dependency
*If you receive an error while running the go get command with text
including “incorrect version” and ”could not read Username” you need
to set an environment variable

go env -w GOPRIVATE=github.com/yourusername

What does it say? It says our repository is private and go should not
use the proxy service (goproxy.io) check its validity by checksum.

86
Lecture 05 - Introduction to Golang

Where the packages are


downloaded
• No longer in the $GOPATH/src but rather in the $GOPATH/pkg
• Notice we have now multiple versions (downloaded earlier) of
greetings package including the one needed

87
Lecture 05 - Introduction to Golang

Running the code

>go run callgreetpackage.go


Hello World-ez >

• For Atom, the script package can now run


go code directly. Use it instead of build

88
Lecture 05 - Introduction to Golang

So far so good but …


• What if we change out local greetings module to say
Bonjour Monde instead of Hello World?

//Package greetings shows the greetings


package greetings

//GreetingsString is a global variable


var GreetingsString = "Bonjour le Monde"

//PrintGreetings is a global function


func PrintGreetings(name string) string {
return GreetingsString + "-" + name
}

89
Lecture 05 - Introduction to Golang

Working locally – the (very) wrong


way
• Running the callgreetpackage.go again doesnt reflect the change 
• We can again publish this on the github say v0.0.2 and then go get,
update go.mod and use the newer version.

90
Lecture 05 - Introduction to Golang

Working locally – the right way


• We can add a replace directive at the go.mod (for the
callgreetings module).

module somename/somepackage
go 1.17
replace github.com/ehteshamz/greetings => ../greetings
require github.com/ehteshamz/greetings v0.0.2 // indirect
• What does it say?

91
Lecture 05 - Introduction to Golang

Greetings in Pashto 
• We change the local version to this but do NOT push this
to github as say v0.0.3

//Package greetings shows the greetings


package greetings

//GreetingsString is a global variable


var GreetingsString = " ‫" سالم نړی‬

//PrintGreetings is a global function


func PrintGreetings(name string) string {
return GreetingsString + "-" + name
}

92
Lecture 05 - Introduction to Golang

Running the main package …

go run callgreetpackage.go
ez-‫سالم نړی‬

93

You might also like