SlideShare a Scribd company logo
Development with Go
- Manjitsing K. Valvi
Pointers
● A variable is a piece of storage containing a value (Variables : Addressable values)
● A pointer value is the address of a variable - the location at which a value is stored
● Not every value has an address, but every variable does.
● We can access the value of a variable indirectly using pointers, without knowing/referring to
name of the variable
● Example:
x := 1 // variable of type int
p := &x // p, of type *int, points to x (&x = address of x)
fmt.Println(*p) // *p denotes value pointed by ‘p’ : "1"
*p = 2 // equivalent to x = 2 ; *p can be on LHS of expr
fmt.Println(x) // "2"
● Expressions that denote variables are the only expressions to which the address-of
operator “&” may be applied
new Function
● new(T)
○ creates unnamed variable of Type T
○ Initializes it to zero value of T
○ Returns it address(type *T)
● new is a predeclared function, not a keyword
● Example:
p := new(int) // p, of type *int, points to an unnamed int variable
fmt.Println(*p) // "0"
*p = 2 // sets the unnamed int to 2
fmt.Println(*p) // "2"
Functions
● It is possible to return multiple values from a function
● Multiple return values are specified between ( and )
● It is possible to return named values from a function, it can be considered as being declared
as a variable in the first line of the function
func arithOps(a, b int)(sum, sub int) { // sum and sub are named
sum = a + b // return values
Sub = a - b
return //no explicit return value, sum and sub are returned when
//return is encountered
}
● Blank identifier ‘ _’ can be used if any value is to be discarded from multiple return values
Variadic Functions
● It is a function that accepts a variable number of arguments
● Here the type of the final parameter is preceded by an ellipsis, "...", showing the function
may be called with any number of arguments of this type
● Useful when number of arguments passed to a function are not known
● Built-in Println is best example of variadic functions
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
sum(1, 2)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4}
sum(nums...)
}
Nested Functions
● In GO functions can be assigned to variables, passed as arguments to other functions and
returned from other functions => First Class Functions
● GO functions can contain functions
● Functions can literally be defined in functions
● Functions can be Anonymous
● Anonymous functions can have parameters like any other function
func main(){
world := func() string { // Anonymous function
fmt.Print("hello world n")
}
world()
fmt.Print("Type of world %T ", world)
}
User Defined Function Types
● In GO user can create his own function types (like struct)
type add func(a int, b int) int // Creating function type add
// with two int parameters
func main() {
var a add = func(a int, b int) int { // variable of type add
return a + b
}
s := a(5, 6) // calling the function a
fmt.Println("Sum", s)
}
Closures
● is a function that references variables outside of its scope
● can outlive the scope in which it was created
● a special case of anonymous functions
● every closure is bound to its own surrounding variable
func main() {
a := 5
func() {
fmt.Println("a =", a) // Anonymous function accessing ‘a’
// variable outside its body
}() // This function is a closure
}
Defer
● defer is useful when one wants to ensure about function getting executed even in case of
failure of the program e.g closing the files, releasing the resources etc
● defer is also helpful in debugging OR in error handling mechanism of GO
func fun(a int) {
fmt.Println("a =",a)
}
func main() {
a := 5
defer fun(a) // deferred function call
fmt.Println("a =", a) // Anonymous function accessing ‘a’
}
// Output is
// a=6 a=5
// Since the call the function fun() is deferred, it is having the
//value of a as 5
Defer
● Syntax : defer func_call( )
● A function or method call can be prefixed with keyword defer
● Such function and argument expressions are evaluated when the statement is
● executed, but the actual call is deferred until the function containing the defer statement
has finished
● No matter whether the function that contains defer statement ends normally or after
panicking, the deferred function is called
● Any number of calls may be deferred; they are executed in the reverse of the order in
which they were deferred
func main() {
a := 5
defer func(a) // deferred function call
fmt.Println("a =", a) // Anonymous function accessing ‘a’
}
References
● https://golangbot.com/first-class-functions/
● https://livebook.manning.com/book/get-programming-with-go/chapter-14/36

More Related Content

What's hot (20)

PPTX
Storage Classes and Functions
Jake Bond
 
PDF
Effective PHP. Part 2
Vasily Kartashov
 
PDF
Effective PHP. Part 4
Vasily Kartashov
 
PDF
Effective PHP. Part 3
Vasily Kartashov
 
PDF
JavaScript: Patterns, Part 3
Chris Farrell
 
PPTX
Storage class
Joy Forerver
 
PPTX
Storage Class Specifiers in C++
Reddhi Basu
 
PDF
Functional programing in Javascript (lite intro)
Nikos Kalogridis
 
PDF
Effective PHP. Part 6
Vasily Kartashov
 
PPTX
Function
jasscheema
 
DOC
What is storage class
Isha Aggarwal
 
PPTX
Functions
preetikapri1
 
PPT
storage class
student
 
PDF
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
PPT
STORAGE CLASSES
sathish sak
 
PPTX
C programming language tutorial
Dr. SURBHI SAROHA
 
PDF
Cpp functions
NabeelaNousheen
 
DOCX
Programming Global variable
imtiazalijoono
 
PPTX
C language (Part 2)
Dr. SURBHI SAROHA
 
PDF
Constructors and Destructors
Dr Sukhpal Singh Gill
 
Storage Classes and Functions
Jake Bond
 
Effective PHP. Part 2
Vasily Kartashov
 
Effective PHP. Part 4
Vasily Kartashov
 
Effective PHP. Part 3
Vasily Kartashov
 
JavaScript: Patterns, Part 3
Chris Farrell
 
Storage class
Joy Forerver
 
Storage Class Specifiers in C++
Reddhi Basu
 
Functional programing in Javascript (lite intro)
Nikos Kalogridis
 
Effective PHP. Part 6
Vasily Kartashov
 
Function
jasscheema
 
What is storage class
Isha Aggarwal
 
Functions
preetikapri1
 
storage class
student
 
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
STORAGE CLASSES
sathish sak
 
C programming language tutorial
Dr. SURBHI SAROHA
 
Cpp functions
NabeelaNousheen
 
Programming Global variable
imtiazalijoono
 
C language (Part 2)
Dr. SURBHI SAROHA
 
Constructors and Destructors
Dr Sukhpal Singh Gill
 

Similar to Pointers & functions (20)

PDF
Golang and Eco-System Introduction / Overview
Markus Schneider
 
PDF
golang_refcard.pdf
Spam92
 
PPTX
Go Programming Language (Golang)
Ishin Vin
 
PPTX
Should i Go there
Shimi Bandiel
 
PPTX
golang_getting_started.pptx
Guy Komari
 
PDF
Golang online course
bestonlinecoursescoupon
 
PDF
Golang
Felipe Mamud
 
PPTX
Introduction to Go
Lorenzo Aiello
 
PPTX
Lab2_AdvancedGoConceptswithgo_foundationofgolang_.pptx
stasneemattia
 
PPTX
Go Language Hands-on Workshop Material
Romin Irani
 
PPTX
Go Language Programming Basic Introduction
johnboladevice
 
PDF
Go Programming by Example_ Nho Vĩnh Share.pdf
Nho Vĩnh
 
PDF
funcs, func expressions, closure, returning funcs, recursion, the stack -goph...
sangam biradar
 
PDF
Go Lang Tutorial
Wei-Ning Huang
 
PPTX
Go programming introduction
Ginto Joseph
 
PDF
Go_ Get iT! .pdf
Gagan Chouhan
 
PPT
Go1
vivekraj3434
 
PPTX
The Go Programing Language 1
İbrahim Kürce
 
PPTX
Golang iran - tutorial go programming language - Preliminary
go-lang
 
PPTX
The GO Language : From Beginners to Gophers
I.I.S. G. Vallauri - Fossano
 
Golang and Eco-System Introduction / Overview
Markus Schneider
 
golang_refcard.pdf
Spam92
 
Go Programming Language (Golang)
Ishin Vin
 
Should i Go there
Shimi Bandiel
 
golang_getting_started.pptx
Guy Komari
 
Golang online course
bestonlinecoursescoupon
 
Golang
Felipe Mamud
 
Introduction to Go
Lorenzo Aiello
 
Lab2_AdvancedGoConceptswithgo_foundationofgolang_.pptx
stasneemattia
 
Go Language Hands-on Workshop Material
Romin Irani
 
Go Language Programming Basic Introduction
johnboladevice
 
Go Programming by Example_ Nho Vĩnh Share.pdf
Nho Vĩnh
 
funcs, func expressions, closure, returning funcs, recursion, the stack -goph...
sangam biradar
 
Go Lang Tutorial
Wei-Ning Huang
 
Go programming introduction
Ginto Joseph
 
Go_ Get iT! .pdf
Gagan Chouhan
 
The Go Programing Language 1
İbrahim Kürce
 
Golang iran - tutorial go programming language - Preliminary
go-lang
 
The GO Language : From Beginners to Gophers
I.I.S. G. Vallauri - Fossano
 
Ad

More from Manjitsing Valvi (14)

PDF
Basic types
Manjitsing Valvi
 
PDF
Basic constructs ii
Manjitsing Valvi
 
PDF
Features of go
Manjitsing Valvi
 
PDF
Error handling
Manjitsing Valvi
 
PDF
Operators
Manjitsing Valvi
 
PDF
Methods
Manjitsing Valvi
 
PDF
Digital marketing marketing strategies for digital world
Manjitsing Valvi
 
PDF
Digital marketing channels
Manjitsing Valvi
 
PDF
Digital marketing techniques
Manjitsing Valvi
 
PDF
Social media marketing & managing cybersocial campaign
Manjitsing Valvi
 
PDF
Creating marketing effective online store
Manjitsing Valvi
 
PDF
Social media marketing tech tools and optimization for search engines
Manjitsing Valvi
 
PDF
Digital marketing managing cybersocial campaign
Manjitsing Valvi
 
PDF
Social media marketing
Manjitsing Valvi
 
Basic types
Manjitsing Valvi
 
Basic constructs ii
Manjitsing Valvi
 
Features of go
Manjitsing Valvi
 
Error handling
Manjitsing Valvi
 
Operators
Manjitsing Valvi
 
Digital marketing marketing strategies for digital world
Manjitsing Valvi
 
Digital marketing channels
Manjitsing Valvi
 
Digital marketing techniques
Manjitsing Valvi
 
Social media marketing & managing cybersocial campaign
Manjitsing Valvi
 
Creating marketing effective online store
Manjitsing Valvi
 
Social media marketing tech tools and optimization for search engines
Manjitsing Valvi
 
Digital marketing managing cybersocial campaign
Manjitsing Valvi
 
Social media marketing
Manjitsing Valvi
 
Ad

Recently uploaded (20)

PPTX
Big Data and Data Science hype .pptx
SUNEEL37
 
PPT
Electrical Safety Presentation for Basics Learning
AliJaved79382
 
PPTX
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
Big Data and Data Science hype .pptx
SUNEEL37
 
Electrical Safety Presentation for Basics Learning
AliJaved79382
 
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Thermal runway and thermal stability.pptx
godow93766
 

Pointers & functions

  • 1. Development with Go - Manjitsing K. Valvi
  • 2. Pointers ● A variable is a piece of storage containing a value (Variables : Addressable values) ● A pointer value is the address of a variable - the location at which a value is stored ● Not every value has an address, but every variable does. ● We can access the value of a variable indirectly using pointers, without knowing/referring to name of the variable ● Example: x := 1 // variable of type int p := &x // p, of type *int, points to x (&x = address of x) fmt.Println(*p) // *p denotes value pointed by ‘p’ : "1" *p = 2 // equivalent to x = 2 ; *p can be on LHS of expr fmt.Println(x) // "2" ● Expressions that denote variables are the only expressions to which the address-of operator “&” may be applied
  • 3. new Function ● new(T) ○ creates unnamed variable of Type T ○ Initializes it to zero value of T ○ Returns it address(type *T) ● new is a predeclared function, not a keyword ● Example: p := new(int) // p, of type *int, points to an unnamed int variable fmt.Println(*p) // "0" *p = 2 // sets the unnamed int to 2 fmt.Println(*p) // "2"
  • 4. Functions ● It is possible to return multiple values from a function ● Multiple return values are specified between ( and ) ● It is possible to return named values from a function, it can be considered as being declared as a variable in the first line of the function func arithOps(a, b int)(sum, sub int) { // sum and sub are named sum = a + b // return values Sub = a - b return //no explicit return value, sum and sub are returned when //return is encountered } ● Blank identifier ‘ _’ can be used if any value is to be discarded from multiple return values
  • 5. Variadic Functions ● It is a function that accepts a variable number of arguments ● Here the type of the final parameter is preceded by an ellipsis, "...", showing the function may be called with any number of arguments of this type ● Useful when number of arguments passed to a function are not known ● Built-in Println is best example of variadic functions func sum(nums ...int) { fmt.Print(nums, " ") total := 0 for _, num := range nums { total += num } fmt.Println(total) } func main() { sum(1, 2) sum(1, 2, 3) nums := []int{1, 2, 3, 4} sum(nums...) }
  • 6. Nested Functions ● In GO functions can be assigned to variables, passed as arguments to other functions and returned from other functions => First Class Functions ● GO functions can contain functions ● Functions can literally be defined in functions ● Functions can be Anonymous ● Anonymous functions can have parameters like any other function func main(){ world := func() string { // Anonymous function fmt.Print("hello world n") } world() fmt.Print("Type of world %T ", world) }
  • 7. User Defined Function Types ● In GO user can create his own function types (like struct) type add func(a int, b int) int // Creating function type add // with two int parameters func main() { var a add = func(a int, b int) int { // variable of type add return a + b } s := a(5, 6) // calling the function a fmt.Println("Sum", s) }
  • 8. Closures ● is a function that references variables outside of its scope ● can outlive the scope in which it was created ● a special case of anonymous functions ● every closure is bound to its own surrounding variable func main() { a := 5 func() { fmt.Println("a =", a) // Anonymous function accessing ‘a’ // variable outside its body }() // This function is a closure }
  • 9. Defer ● defer is useful when one wants to ensure about function getting executed even in case of failure of the program e.g closing the files, releasing the resources etc ● defer is also helpful in debugging OR in error handling mechanism of GO func fun(a int) { fmt.Println("a =",a) } func main() { a := 5 defer fun(a) // deferred function call fmt.Println("a =", a) // Anonymous function accessing ‘a’ } // Output is // a=6 a=5 // Since the call the function fun() is deferred, it is having the //value of a as 5
  • 10. Defer ● Syntax : defer func_call( ) ● A function or method call can be prefixed with keyword defer ● Such function and argument expressions are evaluated when the statement is ● executed, but the actual call is deferred until the function containing the defer statement has finished ● No matter whether the function that contains defer statement ends normally or after panicking, the deferred function is called ● Any number of calls may be deferred; they are executed in the reverse of the order in which they were deferred func main() { a := 5 defer func(a) // deferred function call fmt.Println("a =", a) // Anonymous function accessing ‘a’ }