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

COMP3007_Modern_Programming_Languages (7)

This document provides an introduction to the Go programming language, covering its features, environment setup, basic syntax, functions, packages, and data structures. It highlights Go's simplicity, efficiency, and strong support for concurrency, along with practical examples of variable declarations, control structures, and function syntax. The content is structured for a course titled COMP3007 - Modern Programming Languages, focusing on Go in the Fall 2024-2025 semester.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

COMP3007_Modern_Programming_Languages (7)

This document provides an introduction to the Go programming language, covering its features, environment setup, basic syntax, functions, packages, and data structures. It highlights Go's simplicity, efficiency, and strong support for concurrency, along with practical examples of variable declarations, control structures, and function syntax. The content is structured for a course titled COMP3007 - Modern Programming Languages, focusing on Go in the Fall 2024-2025 semester.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

COMP3007 - Modern Programming Languages

Week 9: Go - Introduction and Basic Syntax

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel

Department of Computer Engineering

Fall 2024-2025

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 1 / 23
Outline

1 Introduction to Go

2 Setting Up Go Environment

3 Basic Syntax

4 Functions

5 Packages and Imports

6 Basic Data Structures

7 Conclusion

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 2 / 23
What is Go?

Go (or Golang) is a statically typed, compiled programming language


Developed by Google in 2007, first released in 2009
Created by Robert Griesemer, Rob Pike, and Ken Thompson
Design goals: simplicity, readability, and efficiency
Compatiblity Promise
Particularly well-suited for networking and multiprocessing

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 3 / 23
Key Features of Go

Fast compilation and efficient execution


Built-in concurrency support (goroutines and channels)
Garbage collection
Strong standard library
Statically linked binaries
Cross-platform support
Simplicity and minimalism in language design

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 4 / 23
Installing Go

Download from official website: https://golang.org/dl/


Available for Windows, macOS, and Linux
Set up GOPATH environment variable
Verify installation: go version

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 5 / 23
Go Toolchain

go build: Compile packages and dependencies


go run: Compile and run Go program
go test: Test packages
go get: Download and install packages and dependencies
go fmt: Gofmt (reformat) package sources
go mod: Module maintenance

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 6 / 23
Hello, World!

1 package main
2
3 import "fmt"
4

5 func main () {
6 fmt. Println ("Hello , World !")
7 }

package main: Declares the package name


import "fmt": Imports the fmt package
func main(): Entry point of the program

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 7 / 23
Variables and Constants

1 var x int = 5
2 y := 10 // Short variable declaration
3

4 const PI = 3.14159
5
6 var (
7 name string = "John"
8 age int = 30
9 )

Variables are declared with var keyword or := syntax


Constants are declared with const keyword
Type inference is available

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 8 / 23
Literals

1 // Integer literals
2 x := 42 // decimal
3 y := 0x2A // hexadecimal
4 z := 052 // octal
5 b := 0b101010 // binary
6
7 // Floating -point literals
8 f1 := 3.14159
9 f2 := 1.23 e2 // scientific notation (123.0)
10 f3 := .5 // can omit leading zero
11
12 // String literals
13 s1 := "Hello\nWorld" // interpreted string literal
14 s2 := `Hello
15 World ` // raw string literal
16
17 // Character literals (rune)
18 c1 := 'A' // simple character
19 c2 := '\u0041 ' // Unicode code point

Go supports various numeric bases for integers


Both interpreted and raw string literals
Unicode characters can be expressed directly or via code points
All numeric literals support ’_’ for readability (e.g., 1_000_000)
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 9 / 23
Basic Data Types
Numeric types:
int, int8, int16, int32, int64
uint, uint8, uint16, uint32, uint64
float32, float64 (never compare two floats without epsilon)
complex64, complex128
Type Value Range Notes
int8 -128 to 127 8-bit signed integer
int16 -32,768 to 32,767 16-bit signed integer
int32 -2,147,483,648 to 2,147,483,647 32-bit signed integer
int64 -9,223,372,036,854,775,808 to 64-bit signed integer
9,223,372,036,854,775,807
uint8 0 to 255 8-bit unsigned integer
uint16 0 to 65,535 16-bit unsigned integer
uint32 0 to 4,294,967,295 32-bit unsigned integer
uint64 0 to 18,446,744,073,709,551,615 64-bit unsigned integer
int Platform dependent At least 32 bits
uint Platform dependent At least 32 bits

Boolean type: bool


String type: string
Derived types:
Arrays, Slices, Maps, Structs
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 10 / 23
Type Conversions - Automatic

1
2 // Automatic type conversion in assignments is NOT allowed in Go
3 var i int32 = 100
4 var j int64 = i // Compile error!
5
6 // Automatic conversions in operations also not allowed
7 var f float64 = 3.14
8 var i int = 42
9 sum := f + i // Compile error!
10
11 // Constants have no type until used
12 const x = 100 // Untyped constant
13 var y int32 = x // OK: constant gets type int32
14 var z float64 = x // OK: constant gets type float64

Go is very strict about types - no automatic conversions


Even between different integer types or numeric types
Exception: untyped constants can be used with compatible types
This helps prevent subtle bugs and makes code more explicit

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 11 / 23
Type Conversions - Explicit

1 // Explicit conversion between numeric types


2 var i int32 = 100
3 var j int64 = int64(i) // OK
4 var f float64 = float64 (i) // OK
5
6 // Possible loss of precision
7 var big int64 = 1000000
8 var small int8 = int8(big) // May lose data!
9
10 // String conversions
11 import "strconv"
12
13 // Integer to string
14 str1 := strconv.Itoa (42) // "42"
15 str2 := strconv.FormatInt (-42, 10) // "-42"
16
17 // String to integer
18 num1 , err := strconv.Atoi("42") // 42
19 num2 , err := strconv.ParseInt("42", 10, 64) // 42

Use T(v) syntax for basic type conversions


strconv package for string conversions
Always check for possible data loss
Error handling required for string parsing
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 12 / 23
Variable Declaration: var Versus :=
1 // Using var
2 var name string = "Alice"
3 var age int = 25
4 var isActive = true // Type inference
5
6 // Using :=
7 name := "Bob" // Type inference
8 count := 42
9 isValid := false
10
11 // Multiple declarations
12 var (
13 firstName string = "John"
14 lastName string = "Doe"
15 score int = 100
16 )
17
18 // Multiple short declarations
19 city , population := "London", 8900000
20
21 // Special cases
22 var client *http.Client // Zero value (nil)
23 var sum int // Zero value (0)

var: Can be used inside and outside functions


:=: Can only be used inside functions
var automatically initializes to zero value
:= requires initial value
cannot
:=Yusuf
Dr. Öğr. Üyesi be used
Kürşat Tuncel to
(Department declare
COMP3007
of Computer global
- Modern variables
Engineering)
Programming Languages Fall 2024-2025 13 / 23
Constants in Go
1 // Basic constant declaration
2 const PI = 3.14159
3 const MAX_CONNECTIONS = 100
4
5 // Typed constants
6 const TIMEOUT time.Duration = 30 * time.Second
7 const MAX_INT32 int32 = 2147483647
8
9 // Multiple constants block
10 const (
11 StatusOK = 200
12 StatusError = 500
13 MaxRetries = 3
14 )
15
16 // Using iota for enumerated constants
17 const (
18 Sunday = iota // 0
19 Monday // 1
20 Tuesday // 2
21 Wednesday // 3
22 Thursday // 4
23 Friday // 5
24 Saturday // 6
25 )
26 // Complex iota patterns
27 const (
28 _ = iota // 0 (ignored)
29 KB = 1 << (10 * iota) // 1 << 10 (1024)
30 MB // 1 << 20
31 GB // 1 << 30
32 )
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 14 / 23
Constants in Go. cont.

Constants are immutable values


Can be typed or untyped
iota generates sequential values
Constants must be evaluable at compile time
Can perform arithmetic with constants

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 15 / 23
Naming Rules and Conventions
1 // Valid variable names
2 var userName string // Mixed case , internal
3 var UserName string // Exported variable
4 var i int // Short name ok
5 var maxRetryCount int // Descriptive name
6 _ignoreThis := 42 // Blank identifier
7
8 // Invalid variable names
9 var 1score int // Can't start with number
10 var my -name string // No hyphens allowed
11 var @email string // No special chars
12
13 // Constants naming
14 const (
15 PI = 3.14159 // Common to use uppercase
16 MaxConnections = 100 // Exported constant
17 minBufferSize = 256 // Package -level constant
18 HTTP_TIMEOUT = 30 // Screaming snake case for some constants
19 )

Rules:
Must begin with letter or underscore
Can contain letters, numbers, underscores
Case-sensitive (user � User)
Exported names must start with capital letter
Length: 1 to any number of characters
Dr. Conventions:
Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 16 / 23
Control Structures

1 if x > 0 {
2 fmt. Println (" Positive ")
3 } else if x < 0 {
4 fmt. Println (" Negative ")
5 } else {
6 fmt. Println ("Zero")
7 }
8 for i := 0; i < 5; i++ {
9 fmt. Println (i)
10 }
11 switch day {
12 case " Monday ":
13 fmt. Println (" Start of the week")
14 default :
15 fmt. Println (" Another day")
16 }

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 17 / 23
Function Syntax
1 func add(x int , y int) int {
2 return x + y
3 }
4
5 func swap(x, y string ) (string , string ) {
6 return y, x
7 }
8
9 func main () {
10 result := add (5, 3)
11 fmt. Println ( result )
12
13 a, b := swap("hello ", " world ")
14 fmt. Println (a, b)
15 }

Functions can return multiple values


Parameters of the same type can share a type declaration
Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department
COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 18 / 23
Packages and Imports

1 package main
2
3 import (
4 "fmt"
5 "math"
6 )
7
8 func main () {
9 fmt. Println ("The square root of 4 is", math.Sqrt (4))
10 }

Every Go program is made up of packages


Programs start running in package main
Import statement allows using functions from other packages

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 19 / 23
Arrays and Slices

1 // Array
2 var a [5] int
3
4 // Slice
5 s := [] int {1, 2, 3, 4, 5}
6 s = append (s, 6)

Arrays have a fixed size


Slices are dynamically-sized, flexible view into arrays

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 20 / 23
Maps

1 m := make(map[ string ]int)


2 m[" Answer "] = 42
3 fmt. Println ("The value :", m[" Answer "])
4
5 delete (m, " Answer ")

Maps are Go’s built-in associative data type (hash tables)


Keys can be of any type that is comparable

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 21 / 23
Conclusion

Go provides a simple yet powerful syntax


Key features: strong typing, concurrency support, and efficiency
We’ve covered basic syntax, control structures, and data types
Next week, we’ll dive deeper into Go’s unique features

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 22 / 23
Thank You! Any Questions?

Dr. Öğr. Üyesi Yusuf Kürşat Tuncel (Department


COMP3007
of Computer
- Modern
Engineering)
Programming Languages Fall 2024-2025 23 / 23

You might also like