GO UNIT I Introduction
GO UNIT I Introduction
UNIT I
Prepared By
Mrs. Rutuja Chavan
Dept. of BCA(Sci)
UNIT I
Full GO Course https://youtu.be/yyUHQIec83I
• A compiler, like GCC, to translate the Go code into a language that the
computer will understand
There are many text editors and compilers to choose from. In this
tutorial, we will use an IDE (see below).
Go Install
An IDE (Integrated Development Environment) is used to edit AND compile the code.
Popular IDE's include Visual Studio Code (VS Code), Vim, Eclipse, and Notepad. These
are all free, and they can be used to both edit and debug Go code.
We will use VS Code in our tutorial, which we believe is a good place to start.
•Find the Go extension by the GO team at Google and install the extension
•After the installation is complete, open the command palette by pressing Ctrl +
Shift + p
Create a new file (File > New File). Copy and paste the
following code and save the file as helloworld.go (File
> Save As):
helloworld.go
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
}
Now, run the code: Open a terminal in VS Code and type:
go run .\helloworld.go
Hello World!
Congratulations! You have now written and executed your
first Go program.
If you want to save the program as an executable, type and
run:
go build .\helloworld.go
Go Programming Language
Golang or Go Programming Language is a statically-typed and
procedural programming language having syntax similar to C
language.
It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken
Thompson at Google. But they launched it in 2009 as an open-
source programming language.
It provides a rich standard library, garbage collection, and
dynamic-typing capability , many advanced built-in types such as
variable length arrays and key-value maps etc. and also provides
support for the environment adopting patterns alike to dynamic
languages.
The latest version of the Golang is 1.23 released on 13th August
2024. Here, we are providing a complete tutorial of Golang with
proper examples.
GO SYNTAX
• Go is modern, fast and comes with a powerful standard library.
• Go has built-in concurrency.
• Go uses interfaces as the building blocks of code reusability.
Output:
Hello, World
Example explained
Line 2: import ("fmt") lets us import files included in the fmt package.
Line 3: A blank line. Go ignores white space. Having white spaces in code
makes it more readable.
Hitting the Enter key adds ";" to the end of the line implicitly
(does not show up in the source code).
func main()
{
fmt.Println("Hello World!")
}
Go Compact Code
You can write more compact code, like shown below (this is not
recommended because it makes the code more difficult to read):
Example
Go Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not be
executed).
Example
// This is a comment
package main
import ("fmt")
func main() {
// This is a comment
fmt.Println("Hello World!")
}
Go Multi-line Comments
Example
package main
import ("fmt")
func main() {
/* The code below will print Hello World
to the screen, and it is amazing */
fmt.Println("Hello World!")
}
Tip: It is up to you which you want to use. Normally, we use // for short
comments, and /* */ for longer comments.
Comment to Prevent Code Execution
You can also use comments to prevent the code from being executed.
The commented code can be saved for later reference and troubleshooting.
Example
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
// fmt.Println("This line does not execute")
}
Why Golang?
The main purpose of designing Golang was to eliminate the problems of existing
languages. So let us see the problems that we are facing with Python, Java, C/C++
programming languages:
• Also, all these languages were designed when multi-threading applications were rare,
so not much effective to highly scalable, concurrent and parallel applications.
• Threading consumes 1MB whereas Goroutine consumes 2KB of memory, hence at the
same time, we can have millions of goroutine triggered.
Key Features
// First Go program
package main
Syntax
var variablename type = value
Note: You always have to specify either type or value (or both).
Syntax
variablename := value
Note: In this case, the type of the variable is inferred from the value (means that the compiler
decides the type of the variable, based on the value).
Note: It is not possible to declare a variable using :=, without assigning a value to it.
Variable Declaration With Initial Value
If the value of a variable is known from the start, you can declare the variable and assign
a value to it on one line:
Example
package main
import ("fmt")
func main() {
var student1 string = "John" //type is string
var student2 = "Jane" //type is inferred
x := 2 //type is inferred
fmt.Println(student1)
fmt.Println(student2)
fmt.Println(x)
}
It is possible to assign a value to a variable after it is declared. This is helpful for cases the value is
not initially known.
Example:
package main
import ("fmt")
func main() {
var student1 string
student1 = "John"
fmt.Println(student1)
}
Example
This example shows how to declare multiple variables in the same line:
package main
import ("fmt")
func main() {
var a, b, c, d int = 1, 3, 5, 7
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Note: If you use the type keyword, it is only possible to declare one type of variable per line.
If the type keyword is not specified, you can declare
different types of variables in the same line:
Example
package main
import ("fmt")
func main() {
var a, b = 6, "Hello"
c, d := 7, "World!"
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Go Variable Declaration in a Block
Multiple variable declarations can also be grouped together into a block for greater
readability:
Example
package main
import ("fmt")
func main() {
var (
a int
b int = 1
c string = "hello"
)
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
Go Variable Naming Rules
A variable can have a short name (like x and y) or a more descriptive name (age, price,
carname, etc.).
Go variable naming rules:
1. A variable name must start with a letter or an underscore character (_)
3. A variable name can only contain alpha-numeric characters and underscores (a-z, A-
Z, 0-9, and _ )
4. Variable names are case-sensitive (age, Age and AGE are three different variables)
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
1. Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John“
2. Pascal Case
Each word starts with a capital letter:
MyVariableName = "John“
3. Snake Case
Each my_variable_name word is separated by an underscore character:
= "John"
Go Constants
Syntax
const CONSTNAME type = value
Note: The value of a constant must be assigned when you declare it.
Declaring a Constant
Here is an example of declaring a constant in Go:
Example
package main
import ("fmt")
const PI = 3.14
func main() {
fmt.Println(PI)
}
Constant Rules
• Constant names follow the same naming rules as variables
• Constant names are usually written in uppercase letters (for easy identification and
differentiation from variables)
Constants can be declared both inside and outside of a function
Constant Types
There are two types of constants:
• Typed constants
• Untyped constants
Typed Constants
Typed constants are declared with a defined type:
Example
package main
import ("fmt")
const A int = 1
func main() {
fmt.Println(A)
}
Untyped Constants
Untyped constants are declared without a type:
Example
package main
import ("fmt")
const A = 1
func main() {
fmt.Println(A)
}
Note: In this case, the type of the constant is inferred from the value (means the
compiler decides the type of the constant, based on the value).
Constants: Unchangeable and Read-only
func main() {
const A = 1
A = 2
fmt.Println(A)
}
Result:
./prog.go:8:7: cannot assign to A
Multiple Constants Declaration
package main
import ("fmt")
const (
A int = 1
B = 3.14
C = "Hi!"
)
func main() {
fmt.Println(A)
fmt.Println(B)
fmt.Println(C)
}
Go Output Functions
•Print()
•Println()
•Printf()
The Print() Function
The Print() function prints its arguments with their default format.
Example
func main() {
var i,j string = "Hello","World"
fmt.Print(i)
fmt.Print(j)
}
Result:
HelloWorld
Result:
Example
func main() {
var i,j string = "Hello","World"
fmt.Print(i, "\n")
fmt.Print(j, "\n")
}
Output:
Hello
Example
It is also possible to only use one Print() for printing multiple variables.
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i, "\n",j)
}
Result:
Hello
Example
If we want to add a space between string arguments, we need to use " ":
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
Result:
Hello World
Example
func main() {
var i,j = 10,20
fmt.Print(i,j)
}
Result:
The Println() Function
func main() {
var i,j string = "Hello","World"
fmt.Println(i,j)
}
Result:
Hello World
The Printf() Function
The Printf() function first formats its argument based on the given formatting verb and then prints them.
Here we will use two formatting verbs:
Example
package main
import ("fmt")
func main() {
var i string = "Hello"
var j int = 15
Result:
i has value: Hello and type: string
j has value: 15 and type: int
Formatting Verbs for Printf()
func main() {
var i = 15.5
var txt = "Hello World!" Result:
fmt.Printf("%v\n", i) 15.5
fmt.Printf("%#v\n", i)
fmt.Printf("%v%%\n", i) 15.5
fmt.Printf("%T\n", i)
15.5%
fmt.Printf("%v\n", txt)
fmt.Printf("%#v\n", txt) float64
fmt.Printf("%T\n", txt)
} Hello World!
"Hello World!"
string
Integer Formatting Verbs
The following verbs can be used with the integer data type:
Verb Description
%b Base 2
%d Base 10
%+d Base 10 and always show sign
%o Base 8
%O Base 8, with leading 0o
%x Base 16, lowercase
%X Base 16, uppercase
%#x Base 16, with leading 0x
%4d Pad with spaces (width 4, right justified)
%-4d Pad with spaces (width 4, left justified)
%04d Pad with zeroes (width 4
Integer Formatting Verbs : Example
package main
import ("fmt") Result:
1111
func main() {
var i = 15 15
+15
fmt.Printf("%b\n", i) 17
fmt.Printf("%d\n", i)
fmt.Printf("%+d\n", i) 0o17
fmt.Printf("%o\n", i) f
fmt.Printf("%O\n", i) F
fmt.Printf("%x\n", i)
fmt.Printf("%X\n", i)
0xf
fmt.Printf("%#x\n", i) 15
fmt.Printf("%4d\n", i) 15
fmt.Printf("%-4d\n", i) 0015
fmt.Printf("%04d\n", i)
}
String Formatting Verbs
The following verbs can be used with the string data type:
Verb Description
%s Prints the value as plain string
%q Prints the value as a double-quoted
string
%8s Prints the value as plain string (width 8,
right justified)
%-8s Prints the value as plain string (width 8,
left justified)
%x Prints the value as hex dump of byte
values
%x Prints the value as hex dump with
String Formatting Verbs : Example
package main
import ("fmt") Result:
func main() {
Hello
var txt = "Hello" "Hello"
fmt.Printf("%s\n", txt)
Hello
fmt.Printf("%q\n", txt) Hello
fmt.Printf("%8s\n", txt)
fmt.Printf("%-8s\n", txt) 48656c6c6f
fmt.Printf("%x\n", txt) 48 65 6c 6c 6f
fmt.Printf("% x\n", txt)
}
Boolean Formatting Verbs:
The following verb can be used with the boolean data type:
Verb Description
%t Value of the boolean
operator in true or false
format (same as using
%v)
Boolean Formatting Verbs: Example
package main
import ("fmt") Result:
func main() {
true
var i = true false
var j = false
fmt.Printf("%t\n", i)
fmt.Printf("%t\n", j)
}
Float Formatting Verbs
The following verbs can be used with the float data type:
Verb Description
%e Scientific notation with 'e'
as exponent
%f Decimal point, no exponent
%.2f Default width, precision 2
%6.2f Width 6, precision 2
%g Exponent as needed, only
necessary digits
Float Formatting Verbs: Example
Result:
package main
import ("fmt")
3.141000e+00
func main() { 3.141000
var i = 3.141 3.14
3.14
fmt.Printf("%e\n", i) 3.141
fmt.Printf("%f\n", i)
fmt.Printf("%.2f\n", i)
fmt.Printf("%6.2f\n", i)
fmt.Printf("%g\n", i)
}
Data Types
Data types specify the type of data that a valid Go variable can hold. In Go language,
the type is divided into four categories which are as follows:
1. Basic type: Numbers, strings, and booleans come under this category.
2. Aggregate type: Array and structs come under this category.
3. Reference type: Pointers, slices, maps, functions, and channels come under this
category.
4. Interface type
Here, we will discuss Basic Data Types in the Go language. The Basic Data Types are
further categorized into three subcategories which are:
5. Numbers
6. Booleans
7. Strings
Go Data Types
Data type specifies the size and type of variable values.
Go is statically typed, meaning that once a variable type is defined, it can only store
data of that type.
package main
import ("fmt")
func main() {
var a bool = true // Boolean
var b int = 5 // Integer
var c float32 = 3.14 // Floating point number
var d string = "Hi!" // String
fmt.Println("Boolean: ", a)
fmt.Println("Integer: ", b)
fmt.Println("Float: ", c)
fmt.Println("String: ", d)
}
Result:
Boolean: true
Integer: 5
Float: 3.14
String: Hi!
Boolean Data Type
Example
package main
import ("fmt")
func main() {
var b1 bool = true // typed
A boolean data type is declaration with initial value
var b2 = true // untyped declaration
declared with with initial value
the bool keyword and can var b3 bool // typed declaration
without initial value
only take the b4 := true // untyped declaration
values true or false. with initial value
func main() {
var b1 bool = true // typed declaration with initial value
var b2 = true // untyped declaration with initial value
var b3 bool // typed declaration without initial value
b4 := true // untyped declaration with initial value
Result:
true
true
false
true
Note: Boolean values are mostly used for conditional testing which you will learn more about in the Go Conditions chapter.
Go Integer Data Types
Integer data types are used to store a whole number without decimals, like
35, -50, or 1345000.
Signed integers, declared with one of the int keywords, can store
both positive and negative values:
Example
package main
import ("fmt")
func main() {
var x int = 500
var y int = -4500
fmt.Printf("Type: %T, value: %v", x, x)
fmt.Printf("Type: %T, value: %v", y, y)
}
Result:
package main
import ("fmt")
func main() {
var x uint = 500
var y uint = 4500
fmt.Printf("Type: %T, value: %v", x, x)
fmt.Printf("Type: %T, value: %v", y, y)
}
Result:
func main() {
var x int8 = 1000
fmt.Printf("Type: %T, value: %v", x, x)
}
Result:
./prog.go:5:7: constant 1000 overflows int8
Go Float Data Types
The float data types are used to store positive and negative numbers with a decimal
point, like 35.3, -2.34, or 3597.34987.
The float data type has two keywords:
Size Range
Type
float32 32 bits -3.4e+38 to 3.4e+38.
float64 64 bits -1.7e+308 to
Tip: The default type for float+1.7e+308.
is float64. If you do not
specify a type, the type will be float64.
The float32 Keyword
Example
This example shows how to declare some variables of type float32:
package main
import ("fmt")
func main() {
var x float32 = 123.78
var y float32 = 3.4e+38
fmt.Printf("Type: %T, value: %v\n", x, x)
fmt.Printf("Type: %T, value: %v", y, y)
}
Result:
Example
This example shows how to declare a variable of type float64:
package main
import ("fmt")
func main() {
var x float64 = 1.7e+308
fmt.Printf("Type: %T, value: %v", x, x)
}
Result:
Type: float64, value: 1.7e+308
Which Float Type to Use?
The type of float to choose, depends on the value the variable has to store.
Example
This example will result in an error because 3.4e+39 is out of range for float32:
package main
import ("fmt")
func main() {
var x float32= 3.4e+39
fmt.Println(x)
}
Result:
./prog.go:5:7: constant 3.4e+39 overflows float32
String Data Type
The string data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
Example
package main
import ("fmt")
func main() {
var txt1 string = "Hello!"
var txt2 string
txt3 := "World 1"
Result:
Type: string, value: Hello!
Type: string, value:
Type: string, value: World 1
Complex Numbers:
The complex numbers are divided into
two parts are shown in the below table.
float32 and float64 are also part of these
complex numbers.
Example:
// Valid identifiers:
_geeks23
geeks
gek23sd
Geeks
geeKs
geeks_geeks
// Invalid identifiers:
212geeks
if
default
Keywords or Reserved words are the words in a language that are used for some
internal process or represent some predefined actions. These words are therefore not
allowed to use as an identifier.
Doing this will result in a compile-time error.
There are total 25 keywords present in the Go language as follows:
Rules for Naming Variables:
import "fmt"
func main() {
}
Output:
func main() {
Example
package main
import ("fmt")
func main() {
var a = 15 + 25
fmt.Println(a)
}
O/p
40
Although the + operator is often used to add together two values, it
can also be used to add together a variable and a value, or a variable
and another variable:
Example
package main
import ("fmt")
func main() {
var (
sum1 = 100 + 50 // 150 (100 + 50)
sum2 = sum1 + 250 // 400 (150 + 250)
sum3 = sum2 + sum2 // 800 (400 + 400)
)
fmt.Println(sum3)
}
O/P
800
Go divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Misc Operators
These are used to perform common mathematical
operations.
Arithmetic Operators
Operator Name Description Example Try it
x:= 10 x:= 10
y:= 2 y:= 2
fmt.Println(x*y) fmt.Println(x/y)
} }
Example : MODULO
package main
import ("fmt")
func main() {
x:= 8
y:= 3
fmt.Println(x%y)
}
Example : INCREMENT Example : DECREMENT
package main
package main import ("fmt")
import ("fmt")
func main() {
func main() {
x:= 10
x:= 10
x++ x--
fmt.Println(x) fmt.Println(x)
} }
Assignment Operators
func main() {
var x = 10
fmt.Println(x)
}
The addition assignment operator (+=) adds a value to a variable:
Example
package main
import ("fmt")
func main() {
var x = 10
x +=5
fmt.Println(x)
}
A list of all assignment operators:
func main() {
var x = 5
var y = 3
fmt.Println(x>y) // returns 1 (true) because 5 is greater than 3
}
A list of all comparison operators:
Operator Name Example Try it
== Equal to x == y Try it »
!= Not equal x != y Try it »
> Greater x>y Try it »
than
< Less than x<y Try it »
>= Greater x >= y Try it »
than or
equal to
<= Less than x <= y Try it »
or equal to
Logical Operators
Logical operators are used to determine the logic between variables or values:
<< Zero fill left shift Shift left by pushing zeros in x << 2 Try it »
from the right
>> Signed right shift Shift right by pushing copies x >> 2 Try it »
of the leftmost bit in from
the left, and let the
rightmost bits fall off
// Golang program to illustrate the use of operators
package main
import "fmt"
func main() {
p := 23
q := 60
// Arithmetic Operator - Addition
result1 := p + q
fmt.Printf("Result of p + q = %d\n", result1)
// Relational Operators - ‘=='(Equal To)
result2 := p == q
fmt.Println(result2)
// Relational Operators - ‘!='(Not Equal To)
result3 := p != q
fmt.Println(result3)
Output:
// Logical Operators
if p != q && p <= q {
fmt.Println("True")
}
Result of p + q =
if p != q || p <= q {
fmt.Println("True")
83 false
} true
if !(p == q) {
fmt.Println("True")
True
} True
// Bitwise Operators - & (bitwise AND)
result4 := p & q
True
fmt.Printf("Result of p & q = %d\n", result4) Result of p & q =
// Assignment Operators - “=”(Simple Assignment) 20
p=q
fmt.Println(p)
60
Go Pointer
A pointer is a special kind of variable that is not only used to
store the memory addresses of other variables but also points
where the memory is located and provides ways to find out the
value stored at that memory location.
It is generally termed as a Special kind of Variable because it is
almost declared as a variable but with *(dereferencing operator).
Before we start there are two important operators which we will use in
pointers i.e.
• * Operator also termed as the dereferencing operator used to declare
pointer variable and access the value stored in the address.
• & operator termed as address operator used to returns the address of
a variable or to access the address of a variable to a pointer.
// Golang program to demonstrate the
declaration and initialization of pointers
package main
import "fmt"
func main() { Output:
// taking a normal variable
var x int = 5748 Value stored in x = 5748
Address of x = 0x414020
// declaration of pointer Address of x = 0x414020
var p *int Value stored in variable p = 5748
// initialization of pointer
p = &x
// displaying the result
fmt.Println("Value stored in x = ", x)
fmt.Println("Address of x = ", &x)
fmt.Println("Address of x = ", p)
1. The default value or zero-value of a pointer is always nil. Or you can say that an
uninitialized pointer will always have a nil value.
Example:
// Golang program to demonstrate the nil value of the pointer
package main
import "fmt"
func main() {
var s *int // taking a pointer
fmt.Println("s = ", s) // displaying the result
}
O/P:
s = <nil>
2. Declaration and initialization of the pointers can be
done into a single line.
Example:
var s *int = &a
package main
import "fmt"
func main() {
var y = 458 // using var keyword we are not defining any type with variable
var p = &y // taking a pointer variable using var keyword without specifying
the type
As we know that * operator is also termed as the dereferencing operator. It is not only
used to declare the pointer variable but also used to access the value stored in the
variable which the pointer points to which is generally termed as indirecting or
dereferencing. * operator is also termed as the value at the address of.
Let’s take an example to get a better understandability of this concept:
Example:
// Golang program to illustrate the concept of dereferencing a pointer
package main
iport "fmt"
func main() {
// using var keyword we are not defining any type with variable
var y = 458
// taking a pointer variable using var keyword without specifying the type
var p = &y
fmt.Println("Value stored in y = ", y)
fmt.Println("Address of y = ", &y)
fmt.Println("Value stored in pointer variable p = ", p)
// this is dereferencing a pointer using * operator before a pointer variable to
access the value stored at the variable at which it is pointing
fmt.Println("Value stored in y(*p) = ", *p)
Go Pointers
Variables are the names given to a memory location where the actual data is stored.
To access the stored data we need the address of that particular memory location.
Golang also allows saving a hexadecimal number into a variable using the literal
expression i.e. number starting from 0x is a hexadecimal number.
// Golang program to demonstrate the variables
// storing the hexadecimal values
package main
Example: import "fmt"
In the below program, we are storing func main() {
the hexadecimal number into a
// storing the hexadecimal values in
variable.
variables
But you can see that the type of x := 0xFF
values is int and saved as the decimal
y := 0x9C
or you can say the decimal value of
type int is storing. // Displaying the values
fmt.Printf("Type of variable x is %T\n", x)
But the main point to explain this
example is that we are storing a fmt.Printf("Value of x in hexadecimal is
hexadecimal value(consider it a %X\n", x)
memory address) but it is not a fmt.Printf("Value of x in decimal is %v\n",
pointer as it is not pointing to any
x)
other memory location of another
variable. fmt.Printf("Type of variable y is %T\n", y)
fmt.Printf("Value of y in hexadecimal is
Output:
Type of variable x is int
Value of x in hexadecimal is FF
Value of x in decimal is 255
Type of variable y is int
Value of y in hexadecimal is 9C
Value of y in decimal is 156
A pointer is a special kind of variable that is not
only used to store the memory addresses of other
variables but also points where the memory is
located and provides ways to find out the value
stored at that memory location.
1. The default value or zero-value of a pointer is always nil. Or you can say that an uninitialized
pointer will always have a nil value.
Example:
// Golang program to demonstrate the nil value of the pointer
package main
import "fmt"
func main() {
3. If you are specifying the data type along with the pointer declaration then the pointer
will be able to handle the memory address of that specified data type variable.
For example, if you taking a pointer of string type then the address of the variable that
you will give to a pointer will be only of string data type variable, not any other type.
4. To overcome the above mention problem you can use the Type Inference concept of
the var keyword.
There is no need to specify the data type during the declaration. The type of a pointer
variable can also be determined by the compiler like a normal variable.
Here we will not use the * operator. It will internally determine by the compiler as we are
initializing the variable with the address of another variable.
Example
// taking a pointer variable using var keyword without specifying the type
var p = &y
// this is dereferencing a pointer using * operator before a pointer variable to access the
value stored
// at the variable at which it is pointing
fmt.Println("Value stored in y(*p) = ", *p)
}
Output:
package main
import "fmt"
func main() {
// using var keyword we are not defining any type with variable
var y = 458
// taking a pointer variable using var keyword without specifying the type
var p = &y
fmt.Println("Value stored in y before changing = ", y)
fmt.Println("Address of y = ", &y)
fmt.Println("Value stored in pointer variable p = ", p)
// this is dereferencing a pointer using * operator before a pointer variable to access the
value stored at the variable at which it is pointing
fmt.Println("Value stored in y(*p) Before Changing = ", *p)
// changing the value of y by assigning the new value to the pointer
*p = 500
fmt.Println("Value stored in y(*p) after Changing = ",y)
}
Output:
Value stored in y before changing = 458
Address of y = 0x414020
Value stored in pointer variable p =
0x414020
Value stored in y(*p)
Before Changing = 458
Value stored in y(*p) after Changing =
500
Pointers to a Function in Go
func main() {
// taking a normal variable
var x = 100
fmt.Printf("The value of x before function call is: %d\n", x)
// calling the function by passing the address of the variable x
ptf(&x)
fmt.Printf("The value of x after function call is: %d\n", x)
}
Note: You can also use the short declaration operator(:=) to declare the variables and pointers in above
programs.
Go Pointer
A pointer is a variable that stores the address of another variable. The general form of
a pointer variable declaration is:
var var_name *var-type
A newly declared pointer which has not been assigned to a variable has the nil value.
The address-of operator &, when placed before a variable gives us the memory
address of the variable.
With pointers, we can pass a reference to a variable (for example, as a parameter to a
function), instead of passing a copy of the variable which can reduce memory usage
and increase efficiency.
Go Pointer Example 1
package main
import (
"fmt"
)
Output :
func main() {
x=0
x:=10
changeX(&x)
fmt.Println(x)
}
func changeX(x *int){
*x=0
}
Go Pointer Example 2
package main
import (
"fmt"
)
func main() { Output:
ptr := new(int) Before change ptr 0
fmt.Println("Before change ptr",*ptr)
After change ptr 10
changePtr(ptr)
fmt.Println("After change ptr",*ptr)
}
func changePtr(ptr *int) {
*ptr = 10
}
Strings in Golang
\000 Unicode character with the given 3-digit 8-bit octal code point
\uhhhh Unicode character with the given 4-digit 16-bit hex code point.
Unicode character with the given 8-digit 32-bit hex code point.
\xhh Unicode character with the given 2-digit 8-bit hex code point.
Using backticks(“): Here, the string literals are
created using backticks(“) and also known as raw
literals.
Raw literals do not support escape characters,
can span multiple lines, and may contain any
character except backtick.
It is, generally, used for writing multiple line
message, in the regular expressions, and in HTML.
Example:
// Go program to illustrate string literals
package main
import "fmt"
func main() {
// Creating and initializing a variable with a string literal Using double-quote
My_value_1 := "Welcome to GeeksforGeeks"
// Using backticks
My_value_3 := `Hello!GeeksforGeeks`
The if statement in Go is used to test the condition. If it evaluates to true, the body of
the statement is executed. If it evaluates to false, if block is skipped.
Syntax :
if(boolean_expression) {
/* statement(s) got executed only if the expression results in true */
}
Example : if
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
/* check the boolean condition using if statement */
if( a % 2==0 ) { /* if condition is true then print the following
*/ fmt.Printf("a is even number" )
}
}
o/p
a is even number
Go if-else
Syntax :
if(boolean_expression) {
/
* statement(s) got executed only if the expression results in true */
} else {
/
* statement(s) got executed only if the expression results in false */
}
Go if-else example
package main
import "fmt"
func main() {
var a int = 10;
if ( a%2 == 0 )
{
fmt.Printf("a is even\n");
}
else
{
fmt.Printf("a is odd\n");
}
fmt.Printf("value of a is : %d\n", a);
}
Output:
a is even value of a is : 10
Go If-else example: with input from user
func main() {
fmt.Print("Enter number: ")
var input int
fmt.Scanln(&input)
fmt.Print(input)
if( input % 2==0 )
{
Output:
Enter number: 10 10 is
fmt.Printf(" is even\n" );
even
}
else
{
fmt.Printf(" is odd\n" );
}
}
Go If else-if chain
The else-if and else keyword must be on the same line after the
closing curly brace }.
Go If else-if chain Example
package main
import "fmt"
func main() {
fmt.Print("Enter text: ")
var input int
fmt.Scanln(&input)
if (input < 0 || input > 100) {
fmt.Print("Please enter valid no")
} else if (input >= 0 && input < 50 ) {
fmt.Print(" Fail")
} else if (input >= 50 && input < 60) {
Output:
fmt.Print(" D Grade")
Enter text: 84 A Grade
} else if (input >= 60 && input < 70 ) {
fmt.Print(" C Grade")
} else if (input >= 70 && input < 80) {
fmt.Print(" B Grade")
} else if (input >= 80 && input < 90 ) {
fmt.Print(" A Grade")
} else if (input >= 90 && input <= 100) {
fmt.Print(" A+ Grade")
}
Go Nested if-else
We can also nest the if-else statement to execute one statement from multiple conditions.
Syntax
if( boolean_expression 1) {
/
* statement(s) got executed only if the expression 1 results in t
rue */
if(boolean_expression 2) {
/
* statement(s) got executed only if the expression 2 results in t
rue */
}
}
nested if-else example
package main
import "fmt"
func main() {
var x int = 10
var y int = 20
if( x >=10 )
{
if( y >= 10 )
{
fmt.Printf("Inside nested If Statement \n" );
}
}
fmt.Printf("Value of x is : %d\n", x );
fmt.Printf("Value of y is : %d\n", y );
Output:
Inside nested If Statement Value of x is : 10 Value of y is : 20
Go switch
The Go switch statement executes one The switch statement in Go is more flexible. In
statement from multiple conditions. It is the above syntax, var1 is a variable which can
similar to if-else-if chain statement. be of any type, and val1, val2, ... are possible
values of var1.
Syntax:
switch var1 {
In switch statement, more than one values can
case val1: be tested in a case, the values are presented in
..... a comma separated list
package main
import "fmt"
func main() { Output:
Enter Number: 20 the value is 20
fmt.Print("Enter Number: ")
var input int
fmt.Scanln(&input)
switch (input) { or
case 10: Output:
fmt.Print("the value is 10") Enter Number: 35 It is not
case 20: 10,20,30,40
fmt.Print("the value is 20")
case 30:
fmt.Print("the value is 30")
case 40:
fmt.Print("the value is 40")
default:
fmt.Print(" It is not 10,20,30,40 ")
}
Go switch fallthrough example
import "fmt"
func main() {
k := 30 Outpu
:
switch k {
case 10:
fmt.Println("was <= 10"); fallthrough;
t
case 20:
was <=
fmt.Println("was <= 20"); fallthrough;
30
case 30:
was <=
40
fmt.Println("was <= 30"); fallthrough;
was <=
case 40:
50
fmt.Println("was <= 40"); fallthrough;
was <=
case 50:
60
fmt.Println("was <= 50"); fallthrough;
default
case 60:
case
fmt.Println("was <= 60"); fallthrough;
default:
fmt.Println("default case")
}
Go For Loop
There are two variants of for loop in Go: Counter-controlled iteration and
Condition-controlled iteration.
When the execution of the loop is over, the objects created inside the
loop gets destroyed.
Go For Loop counter-controlled iteration
example:
package main
import "fmt" Outpu
func main() { t:
for a := 0; a < 11; a++ { 0
fmt.Print(a,"\n") 1
2
} 3
} 4
5
As you can see in the above example, loop begins with the 6
initialization stage, variable for i (i:= 0); This is done only once. 7
It is followed by a conditional check i (i < 10). Conditional check is 8
performed in every iteration. 9
10
Output:
This loop will run forever.
This loop will run forever.
This loop will run forever.
This loop will run forever.
Go For - Condition-controlled iteration
The for range construct is useful in many context. It can be used to traverse every item in a
collection.
It is similar to foreach in other languages. But, we still have the index at each iteration in for range
construct.
Syntax:
A break statement is used to break out of the innermost structure in which it occurs. It can b
used in for-loop (counter, condition,etc.), and also in a switch. Execution is continued aft
the ending } of that structure.
Syntax:-
break;
Go Break Statement Example:
package main
import "fmt"
func main() {
var a int = 1
for a < 10{
fmt.Print("Value of a is ",a,"\n")
a++;
if a > 5{
/* terminate the loop using break statement */
break;
}
} }
Output:
Value of a is 1
Value of a is 2
Value of a is 3
Value of a is 4
Value of a is 5
Break statement can also be applied in the
inner loop, and the control flow break out
to the outer loop. Output:
Go Break Statement with Inner Loop:
package main
11
import "fmt" 12
func main() {
var a int
13
var b int 21
for a = 1; a <= 3; a++ {
31
for b = 1; b <= 3; b++ {
if (a == 2 && b == 2) { 32
break; 33
}
fmt.Print(a, " ", b, "\n")
} } }
Go Continue Statement
The continue is used to skip the remaining part of the loop, and then
continues with the next iteration of the loop after checking the condition.
Syntax:-
continue;
Or we can do like
x:
continue:x
Go Continue Statement Example:
package main
import "fmt" Output:
func main() {
/* local variable definition */
value of a: 1
var a int = 1 value of a: 2
/* do loop execution */ value of a: 3
for a < 10 {
if a == 5 {
value of a: 4
/* skip the iteration */ value of a: 6
a = a + 1; value of a: 7
}
continue;
value of a: 8
fmt.Printf("value of a: %d\n", a); value of a: 9
a++;
}
Continue can be also be applied in the inner
loop
package Go
main Continue Statement with Inner Loop
import "fmt"
example:
func main() {
var a int = 1 /* local variable definition */
Output:
var b int = 1 value of a and b is 1
/* do loop execution */ 1
for a = 1; a < 3; a++ { value of a and b is 1
for b = 1; b < 3; b++ {
2
if a == 2 && b == 2 {
/* skip the iteration */ value of a and b is 1
continue; 3
} value of a and b is 2
fmt.Printf("value of a and b is %d %d\ 1
n", a, b);
}
value of a and b is 2
fmt.Printf("value of a and b is %d %d\ 3