SlideShare a Scribd company logo
Overview of Go Language
GoLang
• Critics: There is nothing new in Go
• GoLang Designers: The task of programming
language designer "is consolidation not innovation"
• Less is exponentially more – Rob Pike, Go Designer
• Do Less, Enable More – Russ Cox, Go Tech Lead
Why new programming language
• Computers are faster but not software development
• Dependency management is critical
• Dynamically typed languages such as Python and JS
• Garbage collection and parallel are not well
supported by popular system languages
• Multicore computers
GoLang
• Go Fast
• Go Simple
• Natively complied (similar to C/C++)
• Static typing
• Fully garbage collection supported
• Support for concurrency and networking
• Rich standard library
• System & Server-side programming
• Scalable
• Open source. Inspired by: C, Pascal, CSP
Who
• Robert Griesemer, Ken Thompson, and Rob Pike
started the project in late 2007
• By mid 2008 the language was mostly designed and
the implementation (compiler, runtime) starting to
work
• Ian Lance Taylor and Russ Cox joined in 2008
• Lots of help from many others
• Officially announced in November 2009
• March 2012: Go 1.0
Go Users
• Google services: YouTube, Kubernetes
• Docker
• Dropbox
• eBay
• Facebook
• Lyft
• Uber
• PayPal
Go Usages
• Large scale distributed systems
• Cloud: GCP, Cloud Foundry, Heroku…
• Web development
• Scripting
• System programming
• Open-source project
Popularity
Install Go
• The Go Playground: https://go.dev/play/
• Install Go: https://go.dev/dl/
• Visual Studio Code + extension
• Go packages doc: https://pkg.go.dev/
First Go Program
• Every Go file starts with
package
• import: packages use
• func main: entry of a Go
program
• Can use semicolons to
separate statements
(optional)
• go run file.go
package main
import "fmt" //comments
func main() {
fmt.Println("Hello world!")
}
fmt Package
• Print
• Println
• Printf
• Scan
• Scanln
• Scanf
fmt Package
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scanln(&name)
fmt.Printf("Hello, %s! n", name)
}
Variables
• Go is statically typed similar to C, C++, Pascal
• Implicit type declare
var name = " Hello " //name is string type
• Explicit declare
var name string = " Hello "
• Multiple declare
var x, y int
var (
name string
z int
)
• Multiple init
var x, y int = 1, 2
var (
name = " Hello "
z = 10
)
SIMILAR TO PASCAL
Variables
• Shorthand syntax
• Explicit declare
name string := " Hello " //no need var, := instead =
• Implicit declare
name := " Hello " //type is string
• Keyword const, cannot change value
const SIZE int = 10
Naming convention
• Camel case
• twoWordString
• iAmAPerson
• Global scope
• File scope
• Export global scope: starts with Uppercase
package main
import "fmt" //comments
var numberOne int = 10
var NumberTwo int = 20
func main() {
fmt.Println("Hello world!")
}
Primitive Data Types
• Boolean
• bool: true / false
• Numeric
• Integer: signed, unsigned (8 → 64 bit)
• Signed: int8, int16, int32, int64
• Unsigned: uint8, uint16, uint32, uint64
• Float:
• float32, float64
• Complex: complex64 (32 real, 32 imagine), complex128 (64 +
64)
• Text
• String: sequence of bytes, size varies
• Byte: UTF8
• Rune: UTF32
Primitive Data Types
package main
import "fmt" //comments
func main() {
var a complex64 = 2 + 3i
fmt.Println(a)
fmt.Println(real(a), imag(a))
a = complex(3, 5)
fmt.Println(a)
}
Type conversion
• Downsize or upsize
package main
import "fmt" //comments
func main() {
var i int = 1
var j float32 = float32(i)
j = 5.5
i = int(j)
i = 65
var s string = string(i)
}
String conversion
• strconv package
package main
import "fmt"
import "strconv"
func main() {
i := 65
var s string = strconv.Itoa(i)
}
Operators
• Mathematic: +, -, *, /, %
• Logical: &&, ||, !
• Relational: ==, !=, >, <, >=, <=
• Bitwise:
• & (and)
• | (or)
• ^ (xor, not)
• &^ (and not), 1 if both are 0s
• << (left shift)
• >> (right shift)
Enum
• List of constants
package main
import "fmt"
const (
zero = 0
one = 1
two = "two"
)
func main() {
}
Enum
• Using iota (default 0)
package main
import "fmt"
const (
zero = iota
one
two
)
func main() {
}
Array
• Fixed size
• Index starts at 0
• Declaration
var arr [3]int
• Initialization
nameList := [3]string {"A", "B", "C"}
• Implicit length
var arr […]int = {1, 2, 3}
• Multi dimensional array
var arr2D [2][3]int
Array
• Length of array: len(arr)
• Iterating through the array
for i,value := range arr {
fmt.Println(i, value)
}
• Assign array will copy
Slice
• Think of slice as dynamic array (but actually NOT)
var slc []int = {1, 2, 3}
//does not contain …
• Using make
slc := make([]int, 3) //len is 3
slc1 := make([]int, 0, 5)
//len is 0, cap is 5
• Append
slc = append(slc, 4)
• Assign slice will make reference. Use copy to duplicate
dup := make([]int, len(slc))
copy(dup, slc)
• Length: len(slc)
Slice Operator
• Slice support operator with the syntax
sliceName[low:high]
fmt.Println(slc[0:2])
fmt.Println(slc[0:3])
fmt.Println(slc[1:])
Map
• Similar to dictionary: map[key-type]value-type
student := map[int]string {
1: "A",
2: "B",
3: "C",}
• Using make
student := make(map[int]string)
• Length: len(student)
• Add new element: map[newKey] = value
• Delete: delete(map, key)
• Check existed
val, isExisted := student[5]
//val is empty string
• Slice cannot be key. Array is possible
• Assign will make reference
Struct
• Top level
type student struct {
id int
name string
grade float32
}
• Inline
studentA := struct {
id int
name string}{id:123,
name:"abc"}
• Access member using dot operator “.”
• Assign will make copy (same as array)
Struct
• Literals
student1 := student {
id: 123,
name: "abc",
grade: 5.5,
}
• Struct name and member must be capitalized to be
exported
Struct
• Embedded
type Person struct {
name string
age int
}
type Student struct {
Person //embedded by value
grade float32
}
• Access: student1.Person.name, student1.name
• Tag
type Student struct {
Person
grade float32 `grade must be 0 to 100`
}
Ad

More Related Content

Similar to Lecture 1 - Overview of Go Language 1.pdf (20)

2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyists
tchandy
 
C
CC
C
Jerin John
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
TAlha MAlik
 
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C
gpsoft_sk
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
Javascript
JavascriptJavascript
Javascript
Sunil Thakur
 
A Very Brief Intro to Golang
A Very Brief Intro to GolangA Very Brief Intro to Golang
A Very Brief Intro to Golang
Joshua Haupt
 
Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go Programming
Lin Yo-An
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
Kamal Acharya
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Sikder Tahsin Al-Amin
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
Kenneth Geisshirt
 
introduction to python
 introduction to python introduction to python
introduction to python
Jincy Nelson
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
dreamwidth
 
#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols
Philippe Back
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
Christian Nagel
 
python.pdf
python.pdfpython.pdf
python.pdf
BurugollaRavi1
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyists
tchandy
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
TAlha MAlik
 
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C
gpsoft_sk
 
A Very Brief Intro to Golang
A Very Brief Intro to GolangA Very Brief Intro to Golang
A Very Brief Intro to Golang
Joshua Haupt
 
Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go Programming
Lin Yo-An
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
Kamal Acharya
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
Kenneth Geisshirt
 
introduction to python
 introduction to python introduction to python
introduction to python
Jincy Nelson
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
dreamwidth
 
#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols
Philippe Back
 

Recently uploaded (20)

Preparation of Experimental Animals.pptx
Preparation of Experimental Animals.pptxPreparation of Experimental Animals.pptx
Preparation of Experimental Animals.pptx
klynct
 
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptxSiver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
PriyaAntil3
 
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptxCleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
zainab98aug
 
Year 7 unit Earth and Space slides .pptx
Year 7 unit Earth and Space slides .pptxYear 7 unit Earth and Space slides .pptx
Year 7 unit Earth and Space slides .pptx
boushrasabbagh
 
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmanaAnatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
arturorbal22
 
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open GovernmentICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
David Graus
 
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Professional Content Writing's
 
Fire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptxFire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptx
091HarshikaModi
 
Proprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendonProprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendon
klynct
 
Water Pollution control using microorganisms
Water Pollution control using microorganismsWater Pollution control using microorganisms
Water Pollution control using microorganisms
gerefam247
 
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
Sérgio Sacani
 
Preclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptxPreclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptx
MahitaLaveti
 
The Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infectionsThe Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infections
NABIHANAEEM2
 
Components of the Human Circulatory System.pptx
Components of the Human  Circulatory System.pptxComponents of the Human  Circulatory System.pptx
Components of the Human Circulatory System.pptx
autumnstreaks
 
CORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptxCORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptx
DharaniJajula
 
External Application in Homoeopathy- Definition,Scope and Types.
External Application  in Homoeopathy- Definition,Scope and Types.External Application  in Homoeopathy- Definition,Scope and Types.
External Application in Homoeopathy- Definition,Scope and Types.
AdharshnaPatrick
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...
Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...
Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...
Professional Content Writing's
 
Batteries and fuel cells for btech first year
Batteries and fuel cells for btech first yearBatteries and fuel cells for btech first year
Batteries and fuel cells for btech first year
MithilPillai1
 
Carboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentationCarboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentation
GLAEXISAJULGA
 
Preparation of Experimental Animals.pptx
Preparation of Experimental Animals.pptxPreparation of Experimental Animals.pptx
Preparation of Experimental Animals.pptx
klynct
 
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptxSiver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
PriyaAntil3
 
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptxCleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
zainab98aug
 
Year 7 unit Earth and Space slides .pptx
Year 7 unit Earth and Space slides .pptxYear 7 unit Earth and Space slides .pptx
Year 7 unit Earth and Space slides .pptx
boushrasabbagh
 
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmanaAnatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
arturorbal22
 
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open GovernmentICAI OpenGov Lab: A Quick Introduction | AI for Open Government
ICAI OpenGov Lab: A Quick Introduction | AI for Open Government
David Graus
 
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Discrete choice experiments: Environmental Improvements to Airthrey Loch Lake...
Professional Content Writing's
 
Fire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptxFire Prevention and protection 1123.pptx
Fire Prevention and protection 1123.pptx
091HarshikaModi
 
Proprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendonProprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendon
klynct
 
Water Pollution control using microorganisms
Water Pollution control using microorganismsWater Pollution control using microorganisms
Water Pollution control using microorganisms
gerefam247
 
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
A Massive Black Hole 0.8kpc from the Host Nucleus Revealed by the Offset Tida...
Sérgio Sacani
 
Preclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptxPreclinical Advances in Nuclear Neurology.pptx
Preclinical Advances in Nuclear Neurology.pptx
MahitaLaveti
 
The Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infectionsThe Microbial World. Microbiology , Microbes, infections
The Microbial World. Microbiology , Microbes, infections
NABIHANAEEM2
 
Components of the Human Circulatory System.pptx
Components of the Human  Circulatory System.pptxComponents of the Human  Circulatory System.pptx
Components of the Human Circulatory System.pptx
autumnstreaks
 
CORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptxCORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptx
DharaniJajula
 
External Application in Homoeopathy- Definition,Scope and Types.
External Application  in Homoeopathy- Definition,Scope and Types.External Application  in Homoeopathy- Definition,Scope and Types.
External Application in Homoeopathy- Definition,Scope and Types.
AdharshnaPatrick
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...
Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...
Chemistry of Warfare (Chemical weapons in warfare: An in-depth analysis of cl...
Professional Content Writing's
 
Batteries and fuel cells for btech first year
Batteries and fuel cells for btech first yearBatteries and fuel cells for btech first year
Batteries and fuel cells for btech first year
MithilPillai1
 
Carboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentationCarboxylic-Acid-Derivatives.lecture.presentation
Carboxylic-Acid-Derivatives.lecture.presentation
GLAEXISAJULGA
 
Ad

Lecture 1 - Overview of Go Language 1.pdf

  • 1. Overview of Go Language
  • 2. GoLang • Critics: There is nothing new in Go • GoLang Designers: The task of programming language designer "is consolidation not innovation" • Less is exponentially more – Rob Pike, Go Designer • Do Less, Enable More – Russ Cox, Go Tech Lead
  • 3. Why new programming language • Computers are faster but not software development • Dependency management is critical • Dynamically typed languages such as Python and JS • Garbage collection and parallel are not well supported by popular system languages • Multicore computers
  • 4. GoLang • Go Fast • Go Simple • Natively complied (similar to C/C++) • Static typing • Fully garbage collection supported • Support for concurrency and networking • Rich standard library • System & Server-side programming • Scalable • Open source. Inspired by: C, Pascal, CSP
  • 5. Who • Robert Griesemer, Ken Thompson, and Rob Pike started the project in late 2007 • By mid 2008 the language was mostly designed and the implementation (compiler, runtime) starting to work • Ian Lance Taylor and Russ Cox joined in 2008 • Lots of help from many others • Officially announced in November 2009 • March 2012: Go 1.0
  • 6. Go Users • Google services: YouTube, Kubernetes • Docker • Dropbox • eBay • Facebook • Lyft • Uber • PayPal
  • 7. Go Usages • Large scale distributed systems • Cloud: GCP, Cloud Foundry, Heroku… • Web development • Scripting • System programming • Open-source project
  • 9. Install Go • The Go Playground: https://go.dev/play/ • Install Go: https://go.dev/dl/ • Visual Studio Code + extension • Go packages doc: https://pkg.go.dev/
  • 10. First Go Program • Every Go file starts with package • import: packages use • func main: entry of a Go program • Can use semicolons to separate statements (optional) • go run file.go package main import "fmt" //comments func main() { fmt.Println("Hello world!") }
  • 11. fmt Package • Print • Println • Printf • Scan • Scanln • Scanf
  • 12. fmt Package package main import "fmt" func main() { var name string fmt.Print("Enter your name: ") fmt.Scanln(&name) fmt.Printf("Hello, %s! n", name) }
  • 13. Variables • Go is statically typed similar to C, C++, Pascal • Implicit type declare var name = " Hello " //name is string type • Explicit declare var name string = " Hello " • Multiple declare var x, y int var ( name string z int ) • Multiple init var x, y int = 1, 2 var ( name = " Hello " z = 10 ) SIMILAR TO PASCAL
  • 14. Variables • Shorthand syntax • Explicit declare name string := " Hello " //no need var, := instead = • Implicit declare name := " Hello " //type is string • Keyword const, cannot change value const SIZE int = 10
  • 15. Naming convention • Camel case • twoWordString • iAmAPerson • Global scope • File scope • Export global scope: starts with Uppercase package main import "fmt" //comments var numberOne int = 10 var NumberTwo int = 20 func main() { fmt.Println("Hello world!") }
  • 16. Primitive Data Types • Boolean • bool: true / false • Numeric • Integer: signed, unsigned (8 → 64 bit) • Signed: int8, int16, int32, int64 • Unsigned: uint8, uint16, uint32, uint64 • Float: • float32, float64 • Complex: complex64 (32 real, 32 imagine), complex128 (64 + 64) • Text • String: sequence of bytes, size varies • Byte: UTF8 • Rune: UTF32
  • 17. Primitive Data Types package main import "fmt" //comments func main() { var a complex64 = 2 + 3i fmt.Println(a) fmt.Println(real(a), imag(a)) a = complex(3, 5) fmt.Println(a) }
  • 18. Type conversion • Downsize or upsize package main import "fmt" //comments func main() { var i int = 1 var j float32 = float32(i) j = 5.5 i = int(j) i = 65 var s string = string(i) }
  • 19. String conversion • strconv package package main import "fmt" import "strconv" func main() { i := 65 var s string = strconv.Itoa(i) }
  • 20. Operators • Mathematic: +, -, *, /, % • Logical: &&, ||, ! • Relational: ==, !=, >, <, >=, <= • Bitwise: • & (and) • | (or) • ^ (xor, not) • &^ (and not), 1 if both are 0s • << (left shift) • >> (right shift)
  • 21. Enum • List of constants package main import "fmt" const ( zero = 0 one = 1 two = "two" ) func main() { }
  • 22. Enum • Using iota (default 0) package main import "fmt" const ( zero = iota one two ) func main() { }
  • 23. Array • Fixed size • Index starts at 0 • Declaration var arr [3]int • Initialization nameList := [3]string {"A", "B", "C"} • Implicit length var arr […]int = {1, 2, 3} • Multi dimensional array var arr2D [2][3]int
  • 24. Array • Length of array: len(arr) • Iterating through the array for i,value := range arr { fmt.Println(i, value) } • Assign array will copy
  • 25. Slice • Think of slice as dynamic array (but actually NOT) var slc []int = {1, 2, 3} //does not contain … • Using make slc := make([]int, 3) //len is 3 slc1 := make([]int, 0, 5) //len is 0, cap is 5 • Append slc = append(slc, 4) • Assign slice will make reference. Use copy to duplicate dup := make([]int, len(slc)) copy(dup, slc) • Length: len(slc)
  • 26. Slice Operator • Slice support operator with the syntax sliceName[low:high] fmt.Println(slc[0:2]) fmt.Println(slc[0:3]) fmt.Println(slc[1:])
  • 27. Map • Similar to dictionary: map[key-type]value-type student := map[int]string { 1: "A", 2: "B", 3: "C",} • Using make student := make(map[int]string) • Length: len(student) • Add new element: map[newKey] = value • Delete: delete(map, key) • Check existed val, isExisted := student[5] //val is empty string • Slice cannot be key. Array is possible • Assign will make reference
  • 28. Struct • Top level type student struct { id int name string grade float32 } • Inline studentA := struct { id int name string}{id:123, name:"abc"} • Access member using dot operator “.” • Assign will make copy (same as array)
  • 29. Struct • Literals student1 := student { id: 123, name: "abc", grade: 5.5, } • Struct name and member must be capitalized to be exported
  • 30. Struct • Embedded type Person struct { name string age int } type Student struct { Person //embedded by value grade float32 } • Access: student1.Person.name, student1.name • Tag type Student struct { Person grade float32 `grade must be 0 to 100` }
  翻译: