77
Go Nathan Reale

Nathan Reale

  • Upload
    hue

  • View
    53

  • Download
    0

Embed Size (px)

DESCRIPTION

Go. Nathan Reale. Quick History. Developed by Rob Pike, Robert Griesemer, and Ken Thompson beginning in 2007 at Google Released in November 2009 as an open source project Go is still a work in progress, and new packages and features are being added weekly. Standard Data Types. - PowerPoint PPT Presentation

Citation preview

Page 1: Nathan Reale

Go

Nathan Reale

Page 2: Nathan Reale

Quick History Developed by Rob Pike, Robert Griesemer,

and Ken Thompson beginning in 2007 at Google

Released in November 2009 as an open source project

Go is still a work in progress, and new packages and features are being added weekly

2 Go - Nathan Reale

Page 3: Nathan Reale

Standard Data Types• Standard Types: bool, int, float• Array/Slice• String (no general char type)• Pointer• Map• Struct• Function• Interface• Channel

3 Go - Nathan Reale

Page 4: Nathan Reale

Numeric Types uint8, uint16, uint32, uint64 int8, int16, int32, int64 float32, float64 complex64, complex128 Each system has the following predefined:

byte (character) uint int float complex

4 Go - Nathan Reale

Page 5: Nathan Reale

Numeric Types Most type conversions must be given

explicitly On 32-bit systems, int is a 32-bit integer, and

int32 is a 32-bit integer, but they are actually different types

It is easy to convert between different typessomeUint := uint(someInt)

5 Go - Nathan Reale

Page 6: Nathan Reale

Declaration of Variables Variables are declared with the “var” keyword

newly declared variables are initialized to 0

var counter int counter = 10

If a variable is initialized, the type can be inferred

var counter = 10 A variable can also be declared and initialized

in a condensed formcounter := 10

6 Go - Nathan Reale

Page 7: Nathan Reale

Declaration of Variables A var block can be used to declare multiple

variables at oncevar (

counter intindex = 10name = “GO”

)

7 Go - Nathan Reale

Page 8: Nathan Reale

Multiple Assignment Go supports multiple assignment

val1, val2 := 1, 2 This can be used to swap variables easily

val1, val2 = val2, val1

8 Go - Nathan Reale

Page 9: Nathan Reale

Type The “type” keyword works similarly to typedef

in Ctype intSlice []inttype score float

Type is mainly used to declare structs and interfaces

9 Go - Nathan Reale

Page 10: Nathan Reale

Constants The “const” keyword is used to declare

number, string, and Boolean constants The type will be implicitly inferred

const seven = 7 Constants are declared at compile time, so

they can not reference runtime code, such as Math.sin()

Constants can be declared in blocks like regular variables

10 Go - Nathan Reale

Page 11: Nathan Reale

Constants Literal values in Go are very high precision,

until they are forced into a specific typeconst bigNumber = 1 << 100

// bigNumber == 1267650600228229401496703205376

const phi = 1.61803398874989

11 Go - Nathan Reale

Page 12: Nathan Reale

Iota When using a constant block, iota can be used

to define enumerated constants easily iota is initially 0 Each newline or semicolon increments iota Iota can be left off of subsequent lines

const (zero = iotaonetwothreefour

)

12 Go - Nathan Reale

Page 13: Nathan Reale

Arrays• Declaration

var array1 [10]intvar array2 [15]string

• Each Array has a size identified with it, which can be retrieved with len()

len(array1) == 10• All values of the array are initialized to the

zero value for its type

13 Go - Nathan Reale

Page 14: Nathan Reale

Arrays Values can be accessed like C

array[2] = array[4] Unlike in C, arrays are values

array3 = array4 // Copies entire array Each type and size combination are distinct

array1 := [10]int{}array2 := [20]int{}array1 = array2 // Will not work

14 Go - Nathan Reale

Page 15: Nathan Reale

Arrays Arrays can be populated and declared at the

same timearray3 := [5]int{1, 2, 3, 4, 5}

Specific values of the array can be initializedarray4 := [5]int{3:10}

If an array is being initialized, the size can be left out

array5 := […]int{1, 2, 3, 4, 5} // len(array5) == 5

15 Go - Nathan Reale

Page 16: Nathan Reale

Arrays Because arrays are values, not references, a

copy is passed to a function One way around this is to pass a pointer to

the array to the functionSum(&array1)

Arrays can also be declared with the new keyword, which returns a pointer to the array

arrayPtr := new([10]string)

16 Go - Nathan Reale

Page 17: Nathan Reale

Arrays

Go - Nathan Reale17

Multi-dimensional arraysvar chessBoard = new([8][8]int)

Values can be accessed as expectedfmt.Println(chessBoard[3][4])

Initializing a multi-dimensional array inlinevar chessBoard = [2][2]int{

[2]int{1, 2},[2]int{3, 4}}

Page 18: Nathan Reale

Slices Slices are a reference to a part of an

underlying arrayvar slice1 []int

Generally used instead of arrays The length can be retrieved with len(), and the

capacity with cap() A slice is ostensibly a struct containing a

pointer into an array, a length, and a capacity

18 Go - Nathan Reale

Page 19: Nathan Reale

Slices Slices can be declared to be a reference to a

part of an existing arrayslice1 := array1[0:5]

slice1 := &array1 Can be declared without explicitly declaring

an arrayvar slice2 = []int{1, 2, 3, 4, 5}slice3 := make([]int, 5)

19 Go - Nathan Reale

Page 20: Nathan Reale

Slices In Go, slices are used to create growable

arrays that have very little overhead

// Create a slice with a capacity of 100names := make([]string, 0, 100)

// Add a name to the slicelength := len(names)names = names[0:length+1]names[length] = “Bill Gates”

20 Go - Nathan Reale

Page 21: Nathan Reale

Strings Strings act like immutable byte arrays

message := “Triangle - ⟁” Individual elements can be accessed

message[3] == ‘a’ Slices can be taken from strings

message[0:8] == “Triangle” len(string) returns the length of the string

21 Go - Nathan Reale

Page 22: Nathan Reale

Pointers

Go - Nathan Reale22

Go has pointers, but no pointer arithmetic There is no way to deallocate memory that is

referenced by a pointer, so there is no way to get a have a NULL pointer

This provides safety while still having the power of pointers

Go handles most pointer operations, including automatically dereferencing the pointer

Page 23: Nathan Reale

Maps Maps are built in hash tables/dictionaries The following maps from strings to int

var map1 map[string] int To initialize the map

m1 := map[string]float{ “Pi”:3.1415 }m2 := make(map[string]float)

To access a value in the map pi := m1[“Pi”]

23 Go - Nathan Reale

Page 24: Nathan Reale

Maps A common idiom in Go is “comma ok”, where

a function returns 2 values, and the second is used as a status or error

phi, ok := m1[“Phi”] If ok is true, then the value was in the map, if

ok is false, the value is not in the array, and the zero value is returned

24 Go - Nathan Reale

Page 25: Nathan Reale

Maps Key-Value pairs are deleted from a map using

a similar style, by passing false as a second argument to the assignment function

m1[“Pi”] = 0, false // Delete “Pi” len(map) returns the number of keys in the

map

25 Go - Nathan Reale

Page 26: Nathan Reale

New vs Make new() allocates memory on the heap and

returns a pointer to the allocated item make() returns an actual object that was

created While new is used to allocate memory and

return a pointer, make is used to create more complex types such as slices, maps and channels

26 Go - Nathan Reale

Page 27: Nathan Reale

New vs Make make([]int, 5, 10) creates an underlying array

of size 10, with each value initialized to 0, and then creates a slice referencing the first 5 elements

The underlying array is automatically garbage collected when no slices are left referencing it

27 Go - Nathan Reale

Page 28: Nathan Reale

Structs Structs are similar to C, but also take the

place of classes Structs can be declared and initialized

togethervar date struct { month string; day, year int }

Usually, structs are tied to a typetype Date struct {

month string

day, year int

}

28 Go - Nathan Reale

Page 29: Nathan Reale

Structs Structs can be declared like normal type

var today Datetoday.month = “April”

Structs can also be allocated with new This returns a pointer, but the fields can be

accessed the same way

tomorrow := new(Date)tomorrow.day = 10

29 Go - Nathan Reale

Page 30: Nathan Reale

Structs Struct literals are used to instantiate a struct

with values The field can be specified so values can be given

in any order It is also common to work with a pointer to a struct

and not the actual struct

today := &Date{month:“April” day:8 year:2010}// today.month == “April”

30 Go - Nathan Reale

Page 31: Nathan Reale

Structs Inheritance is achieved by embedding another

type inside struct Fields can be added anonymously

type Event struct { name string; Date }var christmas Eventchristmas.name = “Christmas”christmas.month = “December”christmas.day = 25

31 Go - Nathan Reale

Page 32: Nathan Reale

Structs A struct literal for the previous example would

need to include the definition for the date structepoch := Event{“The Epoch”, Date{ “January”, 1, 1970 }}

The anonymous fields actually have their type as their namefmt.Println(epoch.Date);

32 Go - Nathan Reale

Page 33: Nathan Reale

Control Structures - If If is very similar to C

if requests <= 0 {quit()

} else {runTask()

} Parenthesis are not required around the

condition, but the braces are required

33 Go - Nathan Reale

Page 34: Nathan Reale

Control Structures - If An alternate form of the if statement includes

an initialization statement

if phi, ok := map[“Phi”]; ok {fmt.Printf(“Φ is %f\n”,phi)

} else {fmt.Println(“Φ is not declared”)

}

34 Go - Nathan Reale

Page 35: Nathan Reale

Control Structures – For There are four forms of the for statement in

Go For acts like the standard C for

for i:=0; i<10; i++ {fmt.Println(i)

}

35 Go - Nathan Reale

Page 36: Nathan Reale

Control Structures – For For acts like the C while

sum := 1for sum < 100 {

sum += sum}

36 Go - Nathan Reale

Page 37: Nathan Reale

Control Structures – For For acts like an infinite loop

for {fmt.Println(time.Seconds)

}

37 Go - Nathan Reale

Page 38: Nathan Reale

Control Structures – For For acts like a foreach loop over an array or

map

values := make(map[string]int)

sum := 0for _, value := range values {

sum += value}

38 Go - Nathan Reale

Page 39: Nathan Reale

Control Structures – Switch Switch acts similarly to switch in C, but there

are a few key differences The value being switched on does not have to be a

constant or an integer There is no automatic fall through

The “fallthrough” keyword can be used to force fall through

There is another variant of switch without an argument that evaluates cases until one is found to be true

39 Go - Nathan Reale

Page 40: Nathan Reale

Control Structures – Switchswitch input {

case 1: fmt.Println(“One”)case 2: fmt.Println(“Two”)case 3: fmt.Println(“Three”)default: fmt.Println(“What?”)

}

40 Go - Nathan Reale

Page 41: Nathan Reale

Control Structures – Switch Like an if statement, switch statements can

have an initializing statement There is a form of switch with no argument

and each case is evaluated until a true case is found

switch {case a<10: fmt.Println(“Less Than 10”)case a==10: fmt.Println(“10”)case a>10: fmt.Println(“More Than 10”)

}

41 Go - Nathan Reale

Page 42: Nathan Reale

Switch to Determine Type There is a special idiom to determine the type

of a variable using a switch statement

switch v := value.(type) {case int, float:

fmt.Println(“Number”)case *int:

fmt.Println(“Int Pointer”)case string:

fmt.Println(“String”)default: fmt.Println(“Other”)

}

42 Go - Nathan Reale

Page 43: Nathan Reale

Break and Continue Both work that same as in C A break statement can also have a label

attached, and it will jump to that label Like goto

43 Go - Nathan Reale

Page 44: Nathan Reale

Functions Functions begin with “func”, then name,

parameters, and return valuesfunc sum(s []int) int {

Functions can return multiple values All parameters are passed by value, but

pointers can be used to prevent passing large types, or modify the parameters

Functions can have named return values that can be used within the function They are initialized to the 0 values They are returned with an empty return statement

44 Go - Nathan Reale

Page 45: Nathan Reale

Functionsfunc sum(s []int) (sum int, ok bool) {

if len(s) == 0 {return // returns 0 and false

}for _, value := range s {

sum += value}return sum, true

}// total, ok := sum(values)

45 Go - Nathan Reale

Page 46: Nathan Reale

Defer The defer keyword can be used to postpone

executing a function until the current function returns Used commonly to close files and unlock a mutex

func readFile() {File.open()defer File.close()// More Code

}

46 Go - Nathan Reale

Page 47: Nathan Reale

Function Literals Anonymous functions can be declared and

assigned to a variable- These functions are closures and first

class values

func eval(f func(int)int, param int) int {

return f(param)

}

eval(func(i int)int { return i*i }, 5)

47 Go - Nathan Reale

Page 48: Nathan Reale

Methods on Structs Instead of classes, Go uses methods with a

specific type as the reciever For example, the date struct used earlier

could have a method attached to it to format the date for output

func (d *Date) String() string {return fmt.Sprintf(“%s %d, %d”,

d.month, d.day, d.year)}// fmt.Println(d.String())

48 Go - Nathan Reale

Page 49: Nathan Reale

Methods on Structs The method can be on either a pointer to the

type or the type itself, and will be called the same Using a pointer sends a reference to the function,

while using the type itself sends a copy Methods can also be on primitive types like int The print functions in fmt can print a type

automatically if it overrides the “String” method

49 Go - Nathan Reale

Page 50: Nathan Reale

Methods on Structs If a struct has an anonymous field of a certain

type, it inherits the methods for that type

// Using the event type from before

pi := &Event{ “Pi Day”, {“March”, 14, 2010}}

fmt.Println(pi.String())

50 Go - Nathan Reale

Page 51: Nathan Reale

Packages Go uses packages instead of classes or

modules The “main” function in the “main” package is

where execution starts A function or variable that begins with an

uppercase letter is visible to programs that import that package (no public or private keyword)

fmt.Printf()

51 Go - Nathan Reale

Page 52: Nathan Reale

Packages Packages can be imported using:

import “package_name” import my_name “package_name”

Like var and const, there can be an import block

Functions imported are called by package_name.function_name(params)

52 Go - Nathan Reale

Page 53: Nathan Reale

Packages A package may declare a function called init(),

which is executed before main Most packages should include a make file to

build them Unit tests can be written and automatically

run when compiling a package Name file package_test.go import “testing” Functions begin with Test

53 Go - Nathan Reale

Page 54: Nathan Reale

Packages - fmt

Go - Nathan Reale54

Used for formatted I/O Standard print functions

Print, Printf, Println Printing to File

Fprint, Fprintf, Fprintln Return as string

Sprint, Sprintf, Sprintln

Page 55: Nathan Reale

Packages - flag

Go - Nathan Reale55

Used to parse arguments used when calling the program

Define flags firstvar file = flag.String(“f”, “input.txt”, “Which file to use”)

When the program is called, the value can be specified> parse –f names.txt

Parse Flagsflag.Parse()

Use the flagstartParser(*file)

Non-flag arguments can be retrieved using Arg(i) where i is the index of the argument NArg returns the number of arguments Args returns a slice of the arguments

Page 56: Nathan Reale

Packages – io and ioutil

Go - Nathan Reale56

The io package contains functions for reading/writing to/from various sources

ioutil has four functions that simplify using files ReadAll reads from an io.Reader until an error or

EOF ReadDir reads the files in a directory ReadFile reads an entire file into a slice WriteFile will write a slice to a file

Page 57: Nathan Reale

Packages - Mutex

Go - Nathan Reale57

Declares a mutex type that has the functions Lock() and Unlock()

There also is a reader/writer mutex This is not the preferred way of synchronizing

routines

Page 58: Nathan Reale

Packages - os

Go - Nathan Reale58

Provides access to operating system independent commands

Defines Stdin, Stdout, and Stderr, which can be used to read/write to/from commandline

Defines the File type, which is used to interact with files

Page 59: Nathan Reale

Packages - Other

Go - Nathan Reale59

math - contains various mathematical functions Trig functions Powers Logarithms

net – various functions to handle network connections

rand – generate random numbers regexp – provides regular expression support sort - used to sort arrays strconv – convert strings to/from other data

types strings - functions to manipulate strings time – get current time and manipulate dates

Page 60: Nathan Reale

Packages - Containers

Go - Nathan Reale60

The container package has implementations of the following containers heap list ring vector

Page 61: Nathan Reale

Interfaces Interfaces are abstract types that define a set

of functions to be implemented An interface can be declared with the type

keyword

type PrintInterface interface {Print() string

}

61 Go - Nathan Reale

Page 62: Nathan Reale

Interfaces Unlike Java, types do not have to declare

which interfaces they implement If a type has all the functions required to

implement an interface, then it does implement the interface

Each type can implement multiple interfaces Every type implements the empty interface

type Empty interface {}

62 Go - Nathan Reale

Page 63: Nathan Reale

Interfaces An interface value is a variable that holds

types that implement the interface It is NOT an instance of the interface

A variable of type “Empty” can hold anything Useful for container classes such as vectors or

trees

var e Emptye = new(Date)e = “Hello”

63 Go - Nathan Reale

Page 64: Nathan Reale

Interfaces

Go - Nathan Reale64

Interfaces are used throughout the io package in Go

io defines a reader and a writertype Reader interface {

Read(p []byte) (n int, err os.Error) }type Writer interface {

Write(p []byte) (n int, err os.Error)}

The Fprint function actually takes a writer as its argument, so anything that implements the “Write” function can be used in Fprint

Page 65: Nathan Reale

Interfaces

Go - Nathan Reale65

A further example of this is the buffio package, which implements a buffered writer

The buffered writer takes a writer and returns a writer, so the buffered writer can be used any place that a normal writer can be used

Page 66: Nathan Reale

Goroutine Concurrency is handled in Go via goroutines,

which are lightweight, cheap, thread To start a goroutine, simply put “go” in front

of a function callgo startServer()

go calculatePI(100)

66 Go - Nathan Reale

Page 67: Nathan Reale

Channels In Go, channels are used to communicate

between goroutines Abstractly, a channel is line of communication

that values can be sent through, and pulled out by any function that has access to the channel

Channels are created using makec := make(chan string)

67 Go - Nathan Reale

Page 68: Nathan Reale

Channels To send values into a channel, use “<-”

c <- “Hello” To get values out of a channel, use “<-”

message := <-c<-c

A channel can be closed by using close(c) closed(c) returns true when the channel has

been closed

68 Go - Nathan Reale

Page 69: Nathan Reale

Channels Channels are references, so if they are copied

or passed to functions, they still refer to the same channel This means that channels can be passed to

goroutines, and the two threads can communicate through the channel

Channels can be passed over channelsvar c := make(chan chan int)

69 Go - Nathan Reale

Page 70: Nathan Reale

Channels By default, channels are synchronized so that

a function blocks when sending a value into a channel until another goroutine reads that value

c := chan intgo calcBigEquation(c)// Do stuff while it is calculatingresult := <-c

70 Go - Nathan Reale

Page 71: Nathan Reale

Channels Buffered channels can by made by specifying

a buffer size when creating the channel The buffer size is part of the actual channel, not

the variable referencing the channel For a buffered channel, a function will not block

when it sends a value unless the buffer is full

c := make(chan string, 10)

71 Go - Nathan Reale

Page 72: Nathan Reale

Channels It is possible to prevent blocking on a channel

by using the “comma ok” methodif value, ok := <-c; ok {

// Value received}

The same can be used when sending a value over a channel

if ok := c <- value; ok {// Value sent

}

72 Go - Nathan Reale

Page 73: Nathan Reale

Control Structures - Select The select statement is a specialized switch

for communications where each case is a send or receive over a channel

One of the possible cases will be run at random, and if none can be run, it will block until one can run A default case can be specified that will be run

instead of blockingselect {

case value := <-parse1: // Do something

case value := <-parse2: // Do something

}

73 Go - Nathan Reale

Page 74: Nathan Reale

Control Structures - Select1) Each case is evaluated2) Out of the possible communications that can

complete successfully, one will be chosen at random and run

3) If no case can be run, the default case if run4) If there is no default case, the select blocks

74 Go - Nathan Reale

Page 75: Nathan Reale

Control Structures - Selectfunc storeParsedData(parser1, parser2 chan string, emails []string) {

for {

select {

case email := <-parser1:

// Add to array

case email := <-parser2:

// Add to array

}

}

}

75 Go - Nathan Reale

Page 76: Nathan Reale

Control Structures - Selectfunc storeParsedData(parser1, parser2 chan string, emails []string,

quit chan bool) {

for {select {

case email := <-parser1:// Add to array

case email := <-parser2:// Add to array

case <-quit:return

}}

}

76 Go - Nathan Reale

Page 77: Nathan Reale

Additional Information

Go - Nathan Reale77

golang.org – Official Go website go-lang.cat-v.org – Links to programs written

in Go, resources such as syntax files for popular editors