Go Lang
Go Lang
Golang
$ go version
go version go1.17.3 darwin/amd64
installing Go
$ go help
Go is a tool for managing Go source code.
Usage:
go <command> [arguments]
package main
import "fmt"
// this is a comment
func main() {
fmt.Println("Hello World")
}
types of main.go
func main() {
• multi line comment
/*
/* this is a
multi multi line
line comment
*/ */
fmt.Println("Hello World")
}
Data type
String Number
“Th3e"
Integer Float
“kloud”
78965 0.564
4532 89.05
Boolean Arrays & Slices
[1, 2, 4, 9]
true
[“foo”, “bar”]
false
[7.0, 9.43, 0.65]
Maps
“x” -> 30
1 -> 100
7 + 8 -7 * 19 -7 - 19
String
to uppercase
"kodekloud" “KODEKLOUD”
length
“kodekloud” 9
Why are data types needed ?
Integer
Boolean
1 byte4 bytes
( 32-bit machine)
8 bytes
( 64-bit machine)
why are data types
needed ?
add(1,2) => 3
Dynamic typed
function add (a, b){
return a+b;
}
• Compiler does not enforce the
type system.
add(1,2) => 3
• Better performance.
package main
import ("fmt")
func main() {
name:= "Lisa"
fmt.Println(name)
}
Integer Float
Integers int
1000000 453
Integers
Data Type Memory
543333.2 654.11
Float
(16 bytes)
“cat” “kodekloud”
Boolean bool
(1 byte)
true false
Arrays, Slices and Maps
“Harry”
“Peter” 778866
900900 99.08
89.05
Declaring Variables
• Go is statically typed.
<variable <data
var = <value>
name> type>
Syntax:
package main
import ("fmt")
func main() {
}
>>> go run main.go
Hello World
Printing Variables
Printing a string
main.go
package main
import "fmt"
func main() {
fmt.Print("Hello World")
package main
import "fmt"
func main() {
package main
import "fmt"
func main() {
var name string = "KodeKloud"
var user string = "Harry"
main.go
package main
import "fmt"
func main() {
var name string = "KodeKloud"
var user string = "Harry"
fmt.Print(name)
fmt.Print(user)
}
package main
import ("fmt")
func main() {
var name string = "KodeKloud"
var user string = "Harry"
fmt.Print(name, "\n")
fmt.Print(user)
}
package main
import ("fmt")
func main() {
var name string = "KodeKloud"
var user string = "Harry"
fmt.Println(name)
fmt.Println(user)
}
>>> Marks: 42
Print f
main.go
package main
import ("fmt")
func main() {
var name string = "Joe"
var i int = 78
fmt.Printf("Hey, %v! You have scored %d/100 in Physics", name, i)
}
main.go
package main
import ("fmt")
func main() {
var user string
user = "Harry"
fmt.Println(user)
package main
import ("fmt")
func main() {
var s string
s = 123
fmt.Println(s)
}
>>> go run main.go
Error: cannot use 123 (type untyped int) as type string
in assignment
Shorthand way
main.go
package main
import ("fmt")
func main() {
package main
import ("fmt")
func main() {
var (
s string = "foo"
i int = 5)
fmt.Println(s)
fmt.Println(i)
}
>>> go run main.go
foo
5
Short Variable Declaration
s := “Hello World”
Short Variable Declaration
main.go
package main
import ("fmt")
func main() {
name:= "Lisa"
name = "Peter"
fmt.Println(name)
}
package main
import ("fmt")
func main() {
name:= "Lisa"
name = 12
fmt.Println(name)
{
• Inner blocks can access
// outer block
variables declared within
outer blocks.
{
• Outer blocks cannot
access variables // inner block
declared within inner
blocks. }
}
Inner & Outer Block
main.go
func main() {
city := "London"
{
country := "UK"
fmt.Println(country)
fmt.Println(city)
}
fmt.Println(country)
fmt.Println(city)
}
package main
import ("fmt")
func main() {
name:= "Lisa"
fmt.Println(name)
package main
import ("fmt")
func main() {
fmt.Println(name)
}
package main
import "fmt"
func main() {
var i int
fmt.Printf("%d", i)
}
package main
import "fmt"
func main() {
var fl float64
fmt.Printf("%.2f", fl)
}
Verb Description
int 0
float64 0.0
string “”
bool false
pointers, functions, nil
interfaces, maps
User Input
Scanf
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scanf("%s", &name)
fmt.Println("Hey there, ", name)
}
>>> go run main.go
Enter your name: Priyanka
Hey there, Priyanka
Multiple Input
main.go
package main
import ("fmt")
func main() {
fmt.Println(name, is_muggle)
Hermione false
Scanf return values
the number of
count arguments that the
function writes to
package main
import ("fmt")
func main() {
var a string
var b int
fmt.Print("Enter a string and a number: ")
count, err := fmt.Scanf("%s %d", &a, &b)
fmt.Println("count : ", count)
fmt.Println("error: ", err)
fmt.Println("a: ", a)
fmt.Println("b: ", b)
}
• %T format specifier
package main
import "fmt"
func main() {
var grades int = 42
var message string = "hello world"
var isCheck bool = true
var amount float32 = 5466.54
}
>>> go run main.go
variable grades = 42 is of type int
variable message ='hello world' is of type string
variable isCheck = 'true' is of type bool
variable amount = 5466.54 is of type float32
using reflect.TypeOf()
main.go
package main
import (
"fmt"
"reflect"
)
func main() {
fmt.Printf("Type: %v \n", reflect.TypeOf(1000))
fmt.Printf("Type: %v \n", reflect.TypeOf("priyanka"))
fmt.Printf("Type: %v \n", reflect.TypeOf(46.0))
fmt.Printf("Type: %v \n", reflect.TypeOf(true))
}
>>> go run main.go
Type: int
Type: string
Type: float64
Type: bool
using reflect.TypeOf()
main.go
package main
import (
"fmt"
"reflect")
func main() {
var grades int = 42
var message string = "hello world"
package main
import "fmt"
func main() {
var i int = 90
var f float64 = float64(i)
fmt.Printf("%.2f\n", f)
package main
import "fmt"
func main() {
Itoa()
• converts integer to string
• returns one value – string formed with the given integer.
integer to string
main.go
package main
import (
"fmt"
"strconv")
func main() {
var i int = 42
var s string = strconv.Itoa(i) // convert int to string
fmt.Printf("%q", s)
}
Itoa()
• converts integer to string.
• returns one value – string formed with the given integer.
Atoi()
• converts string to integer.
• returns two values – the corresponding integer, error (if any).
string to integer
main.go
package main
import (
"fmt"
"strconv")
func main() {
var s string = "200"
i, err := strconv.Atoi(s)
fmt.Printf("%v, %T \n", i, i)
fmt.Printf("%v, %T", err, err)
}
package main
import (
"fmt"
"strconv")
func main() {
var s string = "200abc"
i, err := strconv.Atoi(s)
fmt.Printf("%v, %T \n", i, i)
fmt.Printf("%v, %T", err, err)
}
<const <data
const = <value>
name> type>
main.go
Untyped constant
const age = 12
package main
import "fmt"
func main() {
const name = "Harry Potter"
const is_muggle = false
const age = 12
fmt.Printf("%v: %T \n", name, name)
fmt.Printf("%v: %T \n", is_muggle, is_muggle)
fmt.Printf("%v: %T", age, age)
}
>>> go run main.go
Harry Potter: string
false: bool
12: int
Understanding constants
main.go
package main
import "fmt"
func main() {
const name = "Harry Potter"
name = "Hermione Granger"
fmt.Printf("%v: %T \n", name, name)
}
package main
import "fmt"
func main() {
const name
name = "Hermione Granger"
fmt.Printf("%v: %T \n", name, name)
}
package main
import "fmt"
func main() {
const name := "Hermione Granger"
fmt.Printf("%v: %T \n", name, name)
package main
import "fmt"
func main() {
var radius float64 = 5.0
var area float64
area = PI * radius * radius
fmt.Println("Area of Circle is : ", area)
}
>>> go run main.go
Area of Circle is : 78.5
Operators
Operators & Operands
Operator
a + b
Operand Operand
Kinds of Operators
Comparison Arithmetic
Operators Operators
== != < + - *
Assignment Bitwise
Operators Operators
= += -= & |
*= /= %= << >> ^
Kinds of Operators
Logical
Operators
&& || !
Comparison
Operators
Comparison Operators
• common comparisons -
• Does one string match another ?
func main() {
• returns True when the
values are equal. var city string = "Kolkata"
var city_2 string = "Calcutta"
fmt.Println(city == city_2)
}
func main() {
• returns True when the
values are not equal. var city string = "Kolkata"
var city_2 string = "Calcutta"
fmt.Println(city != city_2)
}
• common comparisons -
• Does the sum of two numbers equal a particular value?
+ - *
/ % ++ --
func main() {
• adds the left and right
operand. var a,b string = "foo", "bar"
fmt.Println(a + b)
func main() {
• subtracts the right operand
from the left operand. var a,b string = "foo", "bar"
fmt.Println(a - b)
func main() {
• subtracts the right operand
from the left operand. var a, b float64 = 79.02, 75.66
fmt.Printf("%.2f", a - b)
func main() {
• multiplies both operands.
var a, b int = 12, 2
fmt.Println(a * b)
func main() {
• unary operator.
var i int = 1
• increments the value of the i++
operand by one. fmt.Println(i)
}
func main() {
• unary operator.
var i int = 1
• decrements the value of the i--
operand by one. fmt.Println(i)
}
&& || !
func main() {
• returns true if both the
statements are true. var x int = 10
fmt.Println((x < 100) && (x < 200))
fmt.Println((x < 300) && (x < 0))
• returns false when either of }
the statement is false.
func main() {
• returns true if one of the
statement is true. var x int = 10
fmt.Println((x < 0) || (x < 200))
fmt.Println((x < 0) || (x > 200))
• returns false when both }
statements are false.
= += -=
*= /= %=
func main() {
• assigns left operand with
the value to the right. var x int = 10
var y int
y = x
• x = y fmt.Println(y)
}
func main() {
• assigns left operand with
the addition result. var x, y int = 10, 20
x += y
fmt.Println(x)
• x+= y means x = x + y
}
func main() {
• assigns left operand with
the subtraction result. var x, y int = 10, 20
x -= y
fmt.Println(x)
• x-= y means x = x - y
}
func main() {
• assigns left operand with
the multiplication result. var x, y int = 10, 20
x *= y
fmt.Println(x)
• x*= y means x = x * y
}
func main() {
• assigns left operand with
the quotient of the division. var x, y int = 200, 20
x /= y
fmt.Println(x)
• x/= y means x = x / y
}
func main() {
• assigns left operand with
the remainder of the var x, y int = 210, 20
division. x %= y
fmt.Println(x)
• x%= y means x = x % y
}
& |
bitwise bitwise
AND OR
^ >> <<
func main() {
func main() {
func main() {
func main() {
func main() {
age
YES NO not
eligible age >= 18
eligible
stop
if-else
syntax
if (condition ){
}
main.go
if statement
package main
import "fmt"
func main() {
var a string = "happy"
if a == "happy" {
fmt.Println(a)
}
}
>>> go run main.go
happy
syntax
if condition {
} else {
}
if-else main.go
func main() {
var fruit string = "grapes"
if fruit == "apples" {
fmt.Println("Fruit is apple")
}
else {
fmt.Println("Fruit is not apple")
}
}
>>> go run main.go
syntax error: unexpected else, expecting }
if-else main.go
func main() {
}
>>> go run main.go
Fruit is not apple
if condition_1 {
// execute when condition_1 is true
} else if condition_2 {
/* execute when condition_1 is false,
and condition_2 is true */
} else if condition_3 {
/* execute when condition_1 and 2 are false,
and condition_3 is true */
} else {
// when none of the above conditions are true
}
fruit
fruit = "orange"
YES
fruit == I love
"apple" apples
NO
NO
no appetite
statements
after if
main.go
if-
else-if package main
import "fmt"
else func main() {
statement fruit := "grapes"
if fruit == "apple" {
fmt.Println("I love apples")
} else if fruit == "orange" {
fmt.Println("Oranges are not apples")
} else {
fmt.Println("no appetite")
}
}
>>> go run main.go
no appetite
switch-case
syntax
switch expression {
case value_1:
// execute when expression equals to value_1
case value_2:
// execute when expression equals to value_2
default:
// execute when no match is found
}
switch main.go
func main() {
var i int = 800
100
switch i {
case 10:
fmt.Println("i is 10")
case 100, 200:
fmt.Println("i is either 100 or 200")
default:
fmt.Println("i is neither 0, 100 or 200")
}
}
>>> go run main.go
i is neither
either 100
0, 100
or 200
or 200
main.go
switch {
case condition_1:
// execute when condition_1 is true
case condition_2:
// execute when condition_2 is true
default:
// execute when no condition is true
}
switch with main.go
fmt.Println("Hello World!")
fmt.Println("Hello World!")
fmt.Println("Hello World!")
loop 1 2 3 4
start
i increases by 1
for i=1
fmt.Println("Hello World!")
to 3
1 <= i <=3
// statements
}
for loop
fmt.Println("Hello World")
}
main.go
func main() {
for i := 1; i <= 5; i++ {
fmt.Println(i*i)
}
}
func main() {
i := 1
for i <= 5 {
fmt.Println(i * i)
i += 1
}
}
>>> go run main.go
1
4
9
16
25
main.go
func main() {
sum := 0
for {
sum++ // repeated forever
}
fmt.Println(sum) // never reached
}
Break & Continue
break main.go
func main() {
• the break statement ends
the loop immediately when for i := 1; i <= 5; i++ {
it is encountered. if i == 3 {
break
}
fmt.Println(i)
}
}
>>> go run main.go
1
2
continue main.go
func main() {
• the continue statement
skips the current iteration of for i := 1; i <= 5; i++ {
if i == 3 {
loop and continues with the
continue
next iteration.
}
fmt.Println(i)
}
}
>>> go run main.go
1
2
4
5
Arrays
Arrays
1 2 3 4
array
1 2 3 4 5
elements:
memory
200 204 208 212 216
address:
4 bytes
why we need arrays
90 85 70
grades
Arrays
• fixed length.
array length = 5
elements: 1 2 3 4 5 capacity = 5
memory
address: 200 204 208 212 216
pointer
array declaration
syntax:
<array [<size of <data
var name> the array>] type>
package main
import "fmt"
func main() {
[0 0 0 0 0]
[ ]
array initialization
func main() {
var fruits [2]string = [2]string{"apples", "oranges"}
fmt.Println(fruits)
func main() {
var fruits [2]string = [2]string{"apples", "oranges"}
fmt.Println(len(fruits))
}
grades: 90 86 76 42 85
index: 0 1 2 3 4
grades[1] = > 86
grades[0] = > 90
array indexing main.go
package main
import "fmt"
func main() {
fmt.Println(fruits[2])
package main
import "fmt"
func main() {
fmt.Println(fruits[6])
package main
import "fmt"
func main() {
fmt.Println(grades[i])
}
main.go
}
main.go
0 2 4
arr[2][1] => 64
0 1
arr[1][0] => 4
1 4 16
arr[0][0] => 2
0 1
2 8 64
0 1
main.go
multidimensional
arrays package main
import "fmt"
func main() {
• more flexible
Slice
underlying array
slice 10
20
Length = 4 30
Capacity = 4 97
54
components of a Slice
underlying array
slice 10 0
20 1
len() Length = 4 30 2
cap() Capacity = 5 97 3
54 4
60 5
declaring and initializing a slice
<slice_name> := []<data_type>{<values>}
fmt.Println(slice)
[10 20 30]
declaring and initializing a slice
underlying array
array[start_index : end_index] 10 0
array[0 : 3] 20 1
array[1 : 6] 30 2
array[ : 4] 97 3
array[ : ] 4
54
60 5
main.go
[20 30 40 50 60 70 80]
main.go
arr := [10]int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
slice := arr[1:8]
fmt.Println(slice)
sub_slice := slice[0:3]
fmt.Println(sub_slice)
}
fmt.Println(slice)
fmt.Println(len(slice))
fmt.Println(cap(slice))
}
arr := [10]int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
slice := arr[1:8]
fmt.Println(cap(arr))
fmt.Println(cap(slice))
}
10
9
slice and index numbers
underlying array
slice 10 0
20 0 1
20
30 1 30 2
1000
97 2 1000
97 3
54 3 54 4
60 5
main.go
slice[1] = 9000
fmt.Println("after modification")
fmt.Println(arr)
fmt.Println(slice)
}
>>> go run main.go
[10 20 30 40 50]
[10 20 30]
after modification
[10 9000 30 40 50]
[10 9000 30]
appending to a slice
20 20 20
30 30 30
len = 2
40 900 -90
cap = 3
len = 3
cap = 3 500
len = 4
cap = 6
main.go
package main
func main() {
to a slice arr := [5]int{10, 20, 30, 40, 50}
slice := arr[:2]
slice_2 := arr_2[:2]
fmt.Println(new_slice)
}
package main
copying import "fmt"
dest_slice := make([]int, 3)
fmt.Println(dest_slice)
looping through
package main
a import "fmt"
}
>>> go run main.go
0 => 10
1 => 20
2 => 30
3 => 40
4 => 50
main.go
looping through
package main
a import "fmt"
}
>>> go run main.go
10
20
30
40
50
maps
maps
Key Value
"en" "English"
• unordered collection of key/value pairs.
"fr" "French"
• implemented by hash tables.
"hi" "Hindi"
"ko" "Korean"
declaring and initializing a map
codes["en"] = "English"
fmt.Println(codes)
<map_name> := map[<key_data_type>]<value_data_type>{<key-value-pairs>}
fmt.Println(codes)
map[en:English fr:French]
declaring and initializing a map –
make() function
<map_name> :=
make(map[<key_data_type>]<value_data_type>,
<initial_capacity>)
main.go
fmt.Println(codes)
}
map[]
main.go
length of
package main
a map import "fmt"
func main() {
codes := map[string]string{"en": "English",
• len()
"fr": "French", "hi": "Hindi"}
fmt.Println(len(codes))
3
main.go
accessing
package main
a map import "fmt"
func main() {
codes := map[string]string{"en": "English",
• map[key]
"fr": "French", "hi": "Hindi"}
fmt.Println(codes["en"])
fmt.Println(codes["fr"])
fmt.Println(codes["hi"])
}
>>> go run main.go
English
French
Hindi
getting a key
func main() {
codes := map[string]int{"en": 1, "fr": 2, "hi": 3}
• map[key]
value, found := codes["en"]
fmt.Println(found, value)
value, found = codes["hh"]
fmt.Println(found, value)
}
func main() {
codes := map[string]string{"en": "English",
"fr": "French", "hi": "Hindi"}
for key, value := range codes {
delete(codes, key)
}
fmt.Println(codes)
}
map[]
main.go
truncate
a map package main
import "fmt"
func main() {
codes := map[string]string{"en": "English",
"fr": "French", "hi": "Hindi"}
codes = make(map[string]string)
fmt.Println(codes)
}
map[]
functions
functions
• Reusability
• Abstraction
functions
functions syntax
}
functions syntax
}
functions syntax
addNumbers sum
b
Input Output
return keyword
}
return keyword
sum := a + b
return sum
}
calling a function
<function_name>(<argument(s)>)
addNumbers(2, 3)
sumOfNumbers := addNumbers(2, 3)
naming convention for
functions
• case-sensitive.
parameters vs arguments
func main() {
printGreeeting("Priyanka")
}
func main() {
sumOfNumbers := addNumbers(2, 3)
fmt.Print(sumOfNumbers)
}
func main() {
sum, difference := operation(20, 10)
fmt.Println(sum, difference)
}
30 10
main.go
named
return package main
import "fmt"
values func operation(a int, b int) (sum int, diff int){
sum = a + b
diff = a - b
return
}
func main() {
sum, difference := operation(20, 10)
fmt.Println(sum, " ", difference)
}
30 10
variadic functions
func main() {
printDetails("Joe", "Physics", "Biology")
func main() {
n := 5
result := factorial(n)
fmt.Println("Factorial of", n, "is :", result)
}
return 4 * factorial(3) = 24
return 3 * factorial(2) = 6
return 2 * factorial(1) = 2
1
anonymous
functions
anonymous functions
• Composition
• creating smaller functions that take care of certain piece of logic.
• composing complex function by using different smaller functions.
• Reduces bugs
• Code gets easier to read and understand
use case
1 - Area
radius
2 - Perimeter
3 - Diameter
Circle
main.go
package main
import "fmt"
func main() {
var query int
var radius float64
if query == 1 {
fmt.Println("Result: ",calcArea(radius))
} else if query == 2{
fmt.Println("Result: ",calcPerimeter(radius))
} else if query == 3{
fmt.Println("Result: ",calcDiameter(radius))
} else {
fmt.Println("Invalid query")
}
}
main.go
func main() {
var query int
var radius float64
if query == 1 {
fmt.Println("Result: ",calcArea(radius))
} else if query == 2{
fmt.Println("Result: ",calcPerimeter(radius))
} else if query == 3{
fmt.Println("Result: ",calcDiameter(radius))
} else {
fmt.Println("Invalid query")
}
}
main.go
result := calcFunction(radius)
fmt.Println("Result: ", result)
fmt.Println("Thank you!")
}
main.go
func main() {
var query int
var radius float64
printResult(radius,
if query == 1 { getFunction(query))
fmt.Println("Result: ",calcArea(radius))
} else if query == 2{
fmt.Println("Result: ",calcPerimeter(radius))
} else if query == 3{
fmt.Println("Result: ",calcDiameter(radius))
} else {
fmt.Println("Invalid query")
}
}
main.go
func main() {
printName("Joe")
defer printRollNo(23)
printAddress("street-32")
}
x := 1 0x0301 1
0x0302
0x0303
0x0305
0x0306
pointers
x := 77 0x0301 77
0x0302
operators i := 10
fmt.Printf("%T %v \n", &i, &i)
fmt.Printf("%T %v \n", *(&i), *(&i))
}
i := 10
var ptr_i *int = &i
initializing a pointer
s := "hello"
var ptr_s = &s
initializing a pointer
<pointer_name> := &<variable_name>
s := "hello"
ptr_s := &s
main.go
*<pointer_name>
*<pointer_name> = <new_value>
dereferencing a pointer
memory
memory
address
x := 77 0x0301 77
100
0x0302
0x0303
0x0305
0x0306
*ptr = 100
main.go
• All basic types (int, float, bool, string, array) are passed by
value.
passing by value in functions
memory
func modify(a int) { address
memory
a += 100
} a 0x0301 10
0x0302
func main() { a 0x0303 110
10
a := 10
0x0304
fmt.Println(a)
modify(a) 0x0305
fmt.Println(a) 0x0306
}
main.go
passing by
value in package main
import "fmt"
functions func modify(s string) {
s = "world"
}
func main() {
a := "hello"
fmt.Println(a)
modify(a)
fmt.Println(a)
}
memory
func modify(s *string) { address
memory
*s = "world"
} a 0x0301 "hello"
"world"
0x0302
func main() { s
0x0303
a := "hello"
0x0304
fmt.Println(a)
modify(&a) 0x0305
fmt.Println(a) 0x0306
}
main.go
passing by
reference in package main
import "fmt"
functions func modify(s *string) {
*s = "world"
}
func main() {
a := "hello"
fmt.Println(a)
modify(&a)
fmt.Println(a)
}
>>> go run main.go
hello
world
main.go
passing by
reference in package main
import "fmt"
functions func modify(s []int) {
s[0] = 100
}
• Slices are passed by
reference, by default. func main() {
slice := []int{10, 20, 30}
fmt.Println(slice)
modify(slice)
fmt.Println(slice)
}
>>> go run main.go
[10 20 30]
[100 20 30]
main.go
passing by
package main
reference in import "fmt"
Student
name grades
var s Student
main.go
<variable_name> := new(<struct_name>)
st := new(Student)
main.go
<variable_name> := <struct_name> {
<field_name>: <value>,
<field_name>: <value>,
}
st := Student{
name: "Joe",
rollNo: 12,
}
main.go
func main() {
st := Student{
name: "Joe",
rollNo: 12,
}
fmt.Printf("%+v", st)
}
{name:Joe rollNo:12}
struct - main.go
func main() {
st := Student{"Joe", 12}
fmt.Printf("%+v", st)
}
{name:Joe rollNo:12}
accessing
struct fields
struct - accessing fields
<variable_name>.<field_name>
main.go
struct -
package main
accessing import "fmt"
func main() {
var c Circle
c.x = 5
c.y = 5
c.radius = 5
fmt.Printf("%+v \n", c)
func main() {
var c Circle
c.x = 5
c.y = 5
c.radius = 5
fmt.Printf("%+v \n", c)
fmt.Printf("%+v \n", c.area)
}
== !=
main.go
//code
• This argument is called a `receiver`.
}
//code
//code
}
main.go
Methods package main
import "fmt"
func main() {
c := Circle{radius: 5}
c.calcArea()
fmt.Printf("%+v", c)
}
>>> go run main.go
{radius:5 area:78.5}
main.go
Methods package main
import "fmt"
func main() {
c := Circle{radius: 5}
c.calcArea()
fmt.Printf("%+v", c)
}
>>> go run main.go
{radius:5 area:0}
Method Sets
Method sets
package main
import "fmt"
func main() {
s := Student{name: "Joe", grades: []int{90, 75, 80}}
s.displayName()
fmt.Printf("%.2f%%", s.calculatePercentage())
}
• An interface specifies a method set and is a powerful way to introduce modularity in Go.
• They describe all the methods of a method set by providing the function signature for each
method.
// Method signatures
getRateOfInterest() float64
calcReturn() float64
}
implementing an interface
func main() {
r := rect{length: 3, breadth: 4}
c := square{side: 5}
printData(r)
printData(c)
}