Introduction to Go Programming Basics

COS418 Precept 1
Jan 26th 2022
Go Resources
Go tutorial: 
Go Playground:
 
Basic syntax code in playground: 
https://tinyurl.com/y7rdgqj3https://play.golang.orghttps://tour.golang.org/list
Agenda for Today
Go Basics
Program Structure 
Variables
Functions
Loops
Composite Data Types
OOP in Go 
Exercise Time
// All files start with a package declaration
p
a
c
k
a
g
e
 
m
a
i
n
// Import statements, one package on each line
i
m
p
o
r
t
 
(
 
 
 
 
 
 
"
e
r
r
o
r
s
"
 
 
 
 
 
 
"
f
m
t
"
)
// Main method will be called when the Go
executable is run
f
u
n
c
 
m
a
i
n
(
)
 
{
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
l
n
(
"
H
e
l
l
o
 
w
o
r
l
d
!
"
)
      basic()
      add(
1
, 
2
)
      divide(
3
, 
4
)
      loops()
      slices()
      maps()
      sharks()
}
P
r
o
g
r
a
m
 
S
t
r
u
c
t
u
r
e
A basic Go program contains
Package specification: serves as a
separate namespace, like modules or
libraries in other languages 
Import other packages
Package-level declarations: var, func,
const, type 
// Declare a package-level variable 
v
a
r
 
m
s
g
 
s
t
r
i
n
g
 
=
 
H
e
l
l
o
 
W
o
r
l
d
// Function declaration
f
u
n
c
 
b
a
s
i
c
(
)
 
{
      
// Declare x as a variable, initialized to 0
 
 
 
 
 
 
v
a
r
 
x
 
i
n
t
      
// Declare y as a variable, initialized to 2
 
 
 
 
 
 
v
a
r
 
y
 
i
n
t
 
=
 
2
      
// Declare z as a variable, initialized to 4
      // This syntax can only be used in a function
      
z := 
4
      
// Assign values to variables
      
x = 
1
      
y = 
2
      
z = x + 
2 
* y + 
3
      
// Print the variables; just use %v for most types
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
x
 
=
 
%
v
,
 
y
 
=
 
%
v
,
 
z
 
=
 
%
v
\
n
"
,
 
x
,
 
y
,
 
z
)
      
// Print the package-level string variable 
      fmt.Println(msg)
}
V
a
r
i
a
b
l
e
s
Variable Declaration
The General form
var name type = expression
= expression
” may be omitted. The
variable will take zero value for the
type, e.g 0 for numbers, false for
boolean, “” for strings, and nil for the
rest
Short Variable Declaration 
name := expression
Only for local variables within a
function
Note: Keep in mind 
:=
 is a declaration,
whereas 
=
 is an assignment
// Function declaration; takes in 2 ints and outputs
an int
f
u
n
c
 
a
d
d
(
x
,
 
y
 
i
n
t
)
 
i
n
t
 
{
 
 
 
 
 
 
r
e
t
u
r
n
 
x
 
+
 
y
}
// Function that returns two things; error is nil if
successful
f
u
n
c
 
d
i
v
i
d
e
(
x
,
 
y
 
i
n
t
)
 
(
f
l
o
a
t
6
4
,
 
e
r
r
o
r
)
 
{
 
 
 
 
 
 
i
f
 
y
 
=
=
 
0
 
{
 
 
 
 
 
 
 
 
 
 
 
 
 
r
e
t
u
r
n
 
0
.
0
,
 
e
r
r
o
r
s
.
N
e
w
(
"
D
i
v
i
d
e
 
b
y
 
z
e
r
o
"
)
      }
      
// Cast x and y to float64 before dividing
 
 
 
 
 
 
r
e
t
u
r
n
 
f
l
o
a
t
6
4
(
x
)
 
/
 
f
l
o
a
t
6
4
(
y
)
,
 
n
i
l
}
F
u
n
c
t
i
o
n
s
Function Declaration
The General Form:
func name (parameter-list) (result-list)
{
body
}
Named functions are declared only at
the package level. 
// squares() returns an anonymous function 
// that itself returns the next square number each
time it is called 
f
u
n
c
 
s
q
u
a
r
e
s
(
)
 
f
u
n
c
(
)
 
i
n
t
 
{
 
 
 
 
 
 
v
a
r
 
x
 
i
n
t
 
 
 
 
 
 
r
e
t
u
r
n
 
f
u
n
c
(
)
 
i
n
t
 
{
 
x++
r
e
t
u
r
n
 
x
*
x
      }
}
f
u
n
c
 
m
a
i
n
(
)
 
{
     // Assign a function variable to func squares()
      f := squares()
      fmt.Println(f()) 
// “1”
      fmt.Println(f()) 
// “4”
      fmt.Println(f()) 
// “9”
}
F
u
n
c
t
i
o
n
s
Anonymous Functions 
Define such a function at its
point of use
Declare without a name
following the 
func
 
keyword
f
u
n
c
 
l
o
o
p
s
(
)
 
{
      
// For loop
 
 
 
 
 
 
f
o
r
 
i
 
:
=
 
0
;
 
i
 
<
 
1
0
;
 
i
+
+
 
{
 
 
 
 
 
 
 
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
(
"
.
"
)
      }
      
// While loop
      
sum := 
1
 
 
 
 
 
 
f
o
r
 
s
u
m
 
<
 
1
0
0
0
 
{
             sum *= 
2
      
}
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
T
h
e
 
s
u
m
 
i
s
 
%
v
\
n
"
,
 
s
u
m
)
}
L
o
o
p
s
In Go, while loops are represented via for
loops
f
u
n
c
 
s
l
i
c
e
s
(
)
 
{
      slice := []int{
1
, 
2
, 
3
, 
4
, 
5
, 
6
, 
7
, 
8
}
      fmt.Println(slice)
      fmt.Println(slice[
2
:
5
]) 
// 3, 4, 5
      
fmt.Println(slice[
5
:]) 
// 6, 7, 8
      
fmt.Println(slice[:
3
]) 
// 1, 2, 3
      
      slice2 := make([]string, 
3
)
 
 
 
 
 
 
s
l
i
c
e
2
[
0
]
 
=
 
"
t
i
c
"
 
 
 
 
 
 
s
l
i
c
e
2
[
1
]
 
=
 
"
t
a
c
"
 
 
 
 
 
 
s
l
i
c
e
2
[
2
]
 
=
 
"
t
o
e
"
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
l
n
(
s
l
i
c
e
2
)
 
 
 
 
 
 
s
l
i
c
e
2
 
=
 
a
p
p
e
n
d
(
s
l
i
c
e
2
,
 
"
t
o
m
"
)
 
 
 
 
 
 
s
l
i
c
e
2
 
=
 
a
p
p
e
n
d
(
s
l
i
c
e
2
,
 
"
r
a
d
a
r
"
)
      fmt.Println(slice2)
 
 
 
 
 
 
f
o
r
 
i
n
d
e
x
,
 
v
a
l
u
e
 
:
=
 
r
a
n
g
e
 
s
l
i
c
e
2
 
{
 
 
 
 
 
 
 
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
%
v
:
 
%
v
\
n
"
,
 
i
n
d
e
x
,
 
v
a
l
u
e
)
      }
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
S
l
i
c
e
 
l
e
n
g
t
h
 
=
 
%
v
\
n
"
,
l
e
n
(
s
l
i
c
e
2
)
)
}
C
o
m
p
o
s
i
t
e
 
D
a
t
a
 
T
y
p
e
s
Composite types are based on basic data
types (e.g integers, floating point
numbers, strings, and booleans). In Go,
some common composite types are:
Array: fixed-length, elements of
same type
Slice: variable-length, elements of
same type
Map: hash table of key value pairs  
Struct: contain arbitrary fields and
types
f
u
n
c
 
m
a
p
s
(
)
 
{
      
// Declare a map whose keys have type string, and values have type int
 
 
 
 
 
 
m
y
M
a
p
 
:
=
 
m
a
k
e
(
m
a
p
[
s
t
r
i
n
g
]
i
n
t
)
 
 
 
 
 
 
m
y
M
a
p
[
"
y
e
l
l
o
w
"
]
 
=
 
1
 
 
 
 
 
 
m
y
M
a
p
[
"
m
a
g
i
c
"
]
 
=
 
2
 
 
 
 
 
 
m
y
M
a
p
[
"
a
m
s
t
e
r
d
a
m
"
]
 
=
 
3
      
fmt.Println(myMap)
 
 
 
 
 
 
m
y
M
a
p
[
"
m
a
g
i
c
"
]
 
=
 
1
0
0
 
 
 
 
 
 
d
e
l
e
t
e
(
m
y
M
a
p
,
 
"
a
m
s
t
e
r
d
a
m
"
)
      fmt.Println(myMap)
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
M
a
p
 
s
i
z
e
 
=
 
%
v
\
n
"
,
 
l
e
n
(
m
y
M
a
p
)
)
}
C
o
m
p
o
s
i
t
e
 
D
a
t
a
 
T
y
p
e
s
:
 
M
a
p
O
b
j
e
c
t
-
O
r
i
e
n
t
e
d
 
P
r
o
g
r
a
m
m
i
n
g
 
(
O
O
P
)
 
i
n
 
G
o
Go also provides programmers with an
OOP paradigm. We can view:
Object: a value or variable that has
methods 
Method: a function associated with
a particular type
Methods in Go 
Method Declaration
Similar to function declaration, but
add an extra parameter between
func
 and 
name
. This will attach the
function to the type of the
parameter.
Example
 
i
m
p
o
r
t
 
m
a
t
h
// Declare a struct named Point with x, y positions
t
y
p
e
 
P
o
i
n
t
 
s
t
r
u
c
t
 
{
 
X
,
 
Y
 
f
l
o
a
t
6
4
}
// Implement a method that find Hypotenuse distance
between one Point and another
f
u
n
c
 
(
p
 
P
o
i
n
t
)
 
D
i
s
t
a
n
c
e
(
q
 
P
o
i
n
t
)
 
f
l
o
a
t
6
4
 
{
 
 
 
 
 
r
e
t
u
r
n
 
m
a
t
h
.
H
y
p
o
t
(
q
.
X
 
-
 
p
.
X
,
 
q
.
Y
 
-
 
p
.
Y
)
}
// standard function 
f
u
n
c
 
D
i
s
t
a
n
c
e
(
p
 
P
o
i
n
t
,
 
q
 
P
o
i
n
t
)
 
f
l
o
a
t
6
4
 
{
 
 
 
 
 
r
e
t
u
r
n
 
m
a
t
h
.
H
y
p
o
t
(
q
.
X
 
-
 
p
.
X
,
 
q
.
Y
 
-
 
p
.
Y
)
}
f
u
n
c
 
m
a
i
n
(
)
 
{
    p := Point{1, 2}
    q := Point{4, 6}
    fmt.Println(p.Distance(q)) 
// “5” method call
    fmt.Println(Distance(p, q)) 
// “5” function call
}
Exercise Time
// Object oriented programming
// Convention: capitalize first letter of public fields
t
y
p
e
 
S
h
a
r
k
 
s
t
r
u
c
t
 
{
      Name string
      Age int
}
// Declare a public method
// This is called a receiver method
f
u
n
c
 
(
s
 
*
S
h
a
r
k
)
 
B
i
t
e
(
)
 
{
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
%
v
 
s
a
y
s
 
C
H
O
M
P
!
\
n
"
,
 
s
.
N
a
m
e
)
}
// Because functions in Go are pass by value
// (as opposed to pass by reference), receiver
// methods generally take in pointers to the
// object instead of the object itself.
f
u
n
c
 
(
s
 
*
S
h
a
r
k
)
 
C
h
a
n
g
e
N
a
m
e
(
n
e
w
N
a
m
e
 
s
t
r
i
n
g
)
 
{
      s.Name = newName
}
// Receiver methods can take in other objects as well
f
u
n
c
 
(
s
 
*
S
h
a
r
k
)
 
G
r
e
e
t
(
s
2
 
*
S
h
a
r
k
)
 
{
 
 
 
 
 
 
i
f
 
(
s
.
A
g
e
 
<
 
s
2
.
A
g
e
)
 
{
 
 
 
 
 
 
 
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
%
v
 
s
a
y
s
 
y
o
u
r
 
m
a
j
e
s
t
y
\
n
"
,
 
s
.
N
a
m
e
)
 
 
 
 
 
 
}
 
e
l
s
e
 
{
 
 
 
 
 
 
 
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
%
v
 
s
a
y
s
 
y
o
 
w
h
a
t
'
s
 
u
p
 
%
v
\
n
"
,
                    s.Name, s2.Name)
      }
}
f
u
n
c
 
s
h
a
r
k
s
(
)
 
{
 
 
 
 
 
 
s
h
a
r
k
1
 
:
=
 
S
h
a
r
k
{
"
B
r
u
c
e
"
,
 
3
2
}
 
 
 
 
 
 
s
h
a
r
k
2
 
:
=
 
S
h
a
r
k
{
"
S
h
a
r
k
i
r
a
"
,
 
4
0
}
      shark1.Bite()
 
 
 
 
 
 
s
h
a
r
k
1
.
C
h
a
n
g
e
N
a
m
e
(
"
L
e
e
"
)
      shark1.Greet(&shark2) 
// pass in pointer
      
shark2.Greet(&shark1)
}
S
h
a
r
k
s
 
a
n
d
 
T
h
e
i
r
 
M
e
t
h
o
d
s
Output:
Bruce says CHOMP!
Lee says your majesty
Sharkira says yo what's up Lee
// Launch n goroutines, each printing a number
// Note how the numbers are not printed in order
f
u
n
c
 
g
o
r
o
u
t
i
n
e
s
(
)
 
{
 
 
 
 
 
 
f
o
r
 
i
 
:
=
 
0
;
 
i
 
<
 
1
0
;
 
i
+
+
 
{
             
// Print the number asynchronously
 
 
 
 
 
 
 
 
 
 
 
 
 
g
o
 
f
m
t
.
P
r
i
n
t
f
(
"
P
r
i
n
t
i
n
g
 
%
v
 
i
n
 
a
 
g
o
r
o
u
t
i
n
e
\
n
"
,
 
i
)
      }
      
// At this point the numbers may not have been printed yet
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
l
n
(
"
L
a
u
n
c
h
e
d
 
t
h
e
 
g
o
r
o
u
t
i
n
e
s
"
)
}
G
o
 
R
o
u
t
i
n
e
s
Possible Output:
Printing 4 in a goroutine
Printing 8 in a goroutine
Printing 9 in a goroutine
Printing 0 in a goroutine
Printing 1 in a goroutine
Printing 6 in a goroutine
Printing 2 in a goroutine
Printing 3 in a goroutine
Launched the goroutines
// Channels are a way to pass messages across goroutines
f
u
n
c
 
c
h
a
n
n
e
l
s
(
)
 
{
 
 
 
 
 
 
c
h
 
:
=
 
m
a
k
e
(
c
h
a
n
 
i
n
t
)
      
// Launch a goroutine using an anonymous function
 
 
 
 
 
 
g
o
 
f
u
n
c
(
)
 
{
             i := 
1
 
 
 
 
 
 
 
 
 
 
 
 
 
f
o
r
 
{
                    
// This line blocks until someone
                    // consumes from the channel
                    
ch <- i * i
                    i++
             }
      }()
      
// Extract first 10 squared numbers from the channel
 
 
 
 
 
 
f
o
r
 
i
 
:
=
 
0
;
 
i
 
<
 
1
0
;
 
i
+
+
 
{
             
// This line blocks until someone sends into the channel
 
 
 
 
 
 
 
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
T
h
e
 
n
e
x
t
 
s
q
u
a
r
e
d
 
n
u
m
b
e
r
 
i
s
 
%
v
\
n
"
,
 
<
-
c
h
)
      }
}
(
U
n
b
u
f
f
e
r
e
d
)
 
C
h
a
n
n
e
l
s
Output:
The next squared number is 1
The next squared number is 4
The next squared number is 9
The next squared number is 16
The next squared number is 25
The next squared number is 36
The next squared number is 49
The next squared number is 64
The next squared number is 81
The next squared number is 100
// Buffered channels are like channels except:
//   1. Sending only blocks when the channel is full
//   2. Receiving only blocks when the channel is empty
f
u
n
c
 
b
u
f
f
e
r
e
d
C
h
a
n
n
e
l
s
(
)
 
{
 
 
 
 
 
 
c
h
 
:
=
 
m
a
k
e
(
c
h
a
n
 
i
n
t
,
 
3
)
      ch <- 
1
      
ch <- 
2
      
ch <- 
3
      
// Buffer is now full; sending any new messages will block
      // Instead let's just consume from the channel
 
 
 
 
 
 
f
o
r
 
i
 
:
=
 
0
;
 
i
 
<
 
3
;
 
i
+
+
 
{
 
 
 
 
 
 
 
 
 
 
 
 
 
f
m
t
.
P
r
i
n
t
f
(
"
C
o
n
s
u
m
i
n
g
 
%
v
 
f
r
o
m
 
c
h
a
n
n
e
l
\
n
"
,
 
<
-
c
h
)
      }
      
// Buffer is now empty; consuming from channel will block
}
B
u
f
f
e
r
e
d
 
C
h
a
n
n
e
l
s
Output:
Consuming 1 from channel
Consuming 2 from channel
Consuming 3 from channel
Slide Note
Embed
Share

Explore the fundamentals of Go programming language including program structure, variables, functions, loops, composite data types, and object-oriented programming concepts. Learn about package declarations, imports, variable declaration, function declaration, and more through practical examples and explanations.

  • Go Programming
  • Basics
  • Variables
  • Functions
  • Loops

Uploaded on Sep 21, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. COS418 Precept 1 Jan 26th 2022

  2. Go Resources Go tutorial: https://tour.golang.org/list Go Playground: https://play.golang.org Basic syntax code in playground: https://tinyurl.com/y7rdgqj3

  3. Agenda for Today Go Basics Program Structure Variables Functions Loops Composite Data Types OOP in Go Exercise Time

  4. // All files start with a package declaration package main Program Structure A basic Go program contains Package specification: serves as a separate namespace, like modules or libraries in other languages Import other packages Package-level declarations: var, func, const, type // Import statements, one package on each line import ( "errors" "fmt" ) // Main method will be called when the Go executable is run func main() { fmt.Println("Hello world!") basic() add(1, 2) divide(3, 4) loops() slices() maps() sharks() }

  5. // Declare a package-level variable var msg string = Hello World Variables // Function declaration func basic() { // Declare x as a variable, initialized to 0 var x int // Declare y as a variable, initialized to 2 var y int = 2 // Declare z as a variable, initialized to 4 // This syntax can only be used in a function z := 4 Variable Declaration The General form var name type = expression = expression may be omitted. The variable will take zero value for the type, e.g 0 for numbers, false for boolean, for strings, and nil for the rest // Assign values to variables x = 1 y = 2 z = x + 2 * y + 3 Short Variable Declaration name := expression Only for local variables within a function // Print the variables; just use %v for most types fmt.Printf("x = %v, y = %v, z = %v\n", x, y, z) // Print the package-level string variable fmt.Println(msg) Note: Keep in mind := is a declaration, whereas = is an assignment }

  6. // Function declaration; takes in 2 ints and outputs an int func add(x, y int) int { return x + y } Functions Function Declaration The General Form: func name (parameter-list) (result-list) { body } Named functions are declared only at the package level. // Function that returns two things; error is nil if successful func divide(x, y int) (float64, error) { if y == 0 { return 0.0, errors.New("Divide by zero") } // Cast x and y to float64 before dividing return float64(x) / float64(y), nil }

  7. // squares() returns an anonymous function // that itself returns the next square number each time it is called func squares() func() int { var x int return func() int { x++ return x*x } } Functions Anonymous Functions Define such a function at its point of use Declare without a name following the func keyword func main() { // Assign a function variable to func squares() f := squares() fmt.Println(f()) // 1 fmt.Println(f()) // 4 fmt.Println(f()) // 9 }

  8. Loops func loops() { // For loop for i := 0; i < 10; i++ { fmt.Print(".") } // While loop sum := 1 for sum < 1000 { sum *= 2 } fmt.Printf("The sum is %v\n", sum) } In Go, while loops are represented via for loops

  9. Composite Data Types func slices() { slice := []int{1, 2, 3, 4, 5, 6, 7, 8} fmt.Println(slice) fmt.Println(slice[2:5]) // 3, 4, 5 fmt.Println(slice[5:]) // 6, 7, 8 fmt.Println(slice[:3]) // 1, 2, 3 slice2 := make([]string, 3) slice2[0] = "tic" slice2[1] = "tac" slice2[2] = "toe" fmt.Println(slice2) slice2 = append(slice2, "tom") slice2 = append(slice2, "radar") fmt.Println(slice2) for index, value := range slice2 { fmt.Printf("%v: %v\n", index, value) } fmt.Printf("Slice length = %v\n", len(slice2)) } Composite types are based on basic data types (e.g integers, floating point numbers, strings, and booleans). In Go, some common composite types are: Array: fixed-length, elements of same type Slice: variable-length, elements of same type Map: hash table of key value pairs Struct: contain arbitrary fields and types

  10. Composite Data Types: Map func maps() { // Declare a map whose keys have type string, and values have type int myMap := make(map[string]int) myMap["yellow"] = 1 myMap["magic"] = 2 myMap["amsterdam"] = 3 fmt.Println(myMap) myMap["magic"] = 100 delete(myMap, "amsterdam") fmt.Println(myMap) fmt.Printf("Map size = %v\n", len(myMap)) }

  11. Object-Oriented Programming (OOP) in Go import math // Declare a struct named Point with x, y positions type Point struct { X, Y float64} Go also provides programmers with an OOP paradigm. We can view: Object: a value or variable that has methods Method: a function associated with a particular type // Implement a method that find Hypotenuse distance between one Point and another func (p Point) Distance(q Point) float64 { return math.Hypot(q.X - p.X, q.Y - p.Y) } Methods in Go Method Declaration Similar to function declaration, but add an extra parameter between func and name. This will attach the function to the type of the parameter. Example // standard function func Distance(p Point, q Point) float64 { return math.Hypot(q.X - p.X, q.Y - p.Y) } func main() { p := Point{1, 2} q := Point{4, 6} fmt.Println(p.Distance(q)) // 5 method call fmt.Println(Distance(p, q)) // 5 function call }

  12. Exercise Time

  13. Output: Bruce says CHOMP! Lee says your majesty Sharkira says yo what's up Lee Sharks and Their Methods // Object oriented programming // Convention: capitalize first letter of public fields type Shark struct { Name string Age int } // Receiver methods can take in other objects as well func (s *Shark) Greet(s2 *Shark) { if (s.Age < s2.Age) { fmt.Printf("%v says your majesty\n", s.Name) } else { fmt.Printf("%v says yo what's up %v\n", s.Name, s2.Name) } } // Declare a public method // This is called a receiver method func (s *Shark) Bite() { fmt.Printf("%v says CHOMP!\n", s.Name) } func sharks() { shark1 := Shark{"Bruce", 32} shark2 := Shark{"Sharkira", 40} shark1.Bite() shark1.ChangeName("Lee") shark1.Greet(&shark2) // pass in pointer shark2.Greet(&shark1) } // Because functions in Go are pass by value // (as opposed to pass by reference), receiver // methods generally take in pointers to the // object instead of the object itself. func (s *Shark) ChangeName(newName string) { s.Name = newName }

  14. Go Routines Possible Output: // Launch n goroutines, each printing a number // Note how the numbers are not printed in order func goroutines() { for i := 0; i < 10; i++ { // Print the number asynchronously go fmt.Printf("Printing %v in a goroutine\n", i) } // At this point the numbers may not have been printed yet fmt.Println("Launched the goroutines") } Printing 4 in a goroutine Printing 8 in a goroutine Printing 9 in a goroutine Printing 0 in a goroutine Printing 1 in a goroutine Printing 6 in a goroutine Printing 2 in a goroutine Printing 3 in a goroutine Launched the goroutines

  15. (Unbuffered) Channels Output: // Channels are a way to pass messages across goroutines func channels() { ch := make(chan int) // Launch a goroutine using an anonymous function go func() { i := 1 for { // This line blocks until someone // consumes from the channel ch <- i * i i++ } }() // Extract first 10 squared numbers from the channel for i := 0; i < 10; i++ { // This line blocks until someone sends into the channel fmt.Printf("The next squared number is %v\n", <-ch) } } The next squared number is 1 The next squared number is 4 The next squared number is 9 The next squared number is 16 The next squared number is 25 The next squared number is 36 The next squared number is 49 The next squared number is 64 The next squared number is 81 The next squared number is 100

  16. Buffered Channels Output: // Buffered channels are like channels except: // 1. Sending only blocks when the channel is full // 2. Receiving only blocks when the channel is empty func bufferedChannels() { ch := make(chan int, 3) ch <- 1 ch <- 2 ch <- 3 // Buffer is now full; sending any new messages will block // Instead let's just consume from the channel for i := 0; i < 3; i++ { fmt.Printf("Consuming %v from channel\n", <-ch) } // Buffer is now empty; consuming from channel will block } Consuming 1 from channel Consuming 2 from channel Consuming 3 from channel

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#