You are on page 1of 20

Go Lang - Lab Manual

UCA20S02J- Go Programming Lab Manual


Tool Used:

repl.it - A Collaborative Browser based IDE

Go Lang - Lab Manual 1


TABLE OF CONTENTS
1. Hello World Program

2. Display sum, product, quotient of two number.

3. Accept a number from console and check if it is between 1 and 10

4. Calculate sum of first n numbers.

5. Create a Slice using Make function

6. Create and initialize map using make function

7. Recursive function to find factorial of a number

8. Write a function that accepts 2 numbers and performs addition, subtraction and
return both values.

9. Write a function with one variadic parameter that finds the greatest number in a
list of n numbers.

10. Write a program to swap two integers

11. Illustrate creation and accessing a structure

12. Program to demonstrate the concept of Interfaces

13. Input the string ‘Hello World’ and slice it into two

14. Program to write a list of cities to a new file

15. Develop concurrent clock server

16. Send and receive data from Channel

TABLE OF CONTENTS 1
1. Hello World Program
package main

import "fmt"

func main() {
fmt.Println("Hello World!")
}

Output:
>go run welcome.go
Hello World!

1. Hello World Program 1


2. Display sum, product,
quotient of two number.
package main

import "fmt"

func main() {
var a, b int
fmt.Println("Finds Sum, Product and Quotient")
fmt.Println("--------------------")
fmt.Print("Enter Two Numbers ")
fmt.Scanf("%d %d", &a, &b)
fmt.Printf("Sum : %d\n", a + b)
fmt.Printf("Product : %d\n", a * b)
fmt.Printf("Quotient : %d\n", a / b)
}

Output:
>go run welcome.go

Finds Sum, Product and Quotient

--------------------

Enter Two Numbers 2 4

Sum : 6

Product : 8
Quotient : 0

2. Display sum, product, quotient of two number. 1


3. Accept a number from
console and check whether it is
between 1 and 10
package main

import "fmt"

func main() {
fmt.Println( "Enter Number: ")
var n int
fmt.Scanln(&n)
if (n >=1 && n<=10) {
fmt.Println(n, "is between 1 and 10" )
}
else {
fmt.Println(n, "is out of range")
}
}

Output:
>go run Check.go

Enter Number: 12
12 is out of range

> go run Check.go

Enter Number: 4
4 is between 1 and 10

3. Accept a number from console and check whether it is between 1 and 10 1


4. Calculate sum of first n
numbers
package main

import "fmt"

func main() {
fmt.Print( "Enter Number: ")
var n int
fmt.Scanln(&n)
sum := 0
for i := 1; i <= n; i++ {
sum += i
}
fmt.Println(sum)
}

Output:
>go run sum1toN.go

Enter Number: 10
55

4. Calculate sum of first n numbers 1


5. Create a Slice using Make
function
package main

import "fmt"

func main() {
a := make([]int, 5)
printSlice("a", a)

b := make([]int, 0, 5)
printSlice("b", b)

c := b[:2]
printSlice("c", c)

d := c[2:5]
printSlice("d", d)
}

func printSlice(s string, x []int) {


fmt.Printf("%s len=%d cap=%d %v\n", s, len(x), cap(x), x)
}

Output:
>go run slice.go

a len=5 cap=5 [0 0 0 0 0]

b len=0 cap=5 []

c len=2 cap=5 [0 0]
d len=3 cap=3 [0 0 0]

5. Create a Slice using Make function 1


6. Create and initialize map
using make function
package main

import "fmt"

func main() {

m := make(map[string]int)

m["k1"] = 7
m["k2"] = 13

fmt.Println("map:", m)

v1 := m["k1"]
fmt.Println("v1: ", v1)

fmt.Println("len:", len(m))

delete(m, "k2")
fmt.Println("map:", m)

_, prs := m["k2"]
fmt.Println("prs:", prs)

n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
}

Output:
go run map.go

map: map[k1:7 k2:13]

v1: 7

len: 2

map: map[k1:7]

prs: false
map: map[bar:2 foo:1]

6. Create and initialize map using make function 1


7. Recursive function to find
factorial of a number
package main

import "fmt"

func factorial(num int) int {


if num == 1 || num == 0 {
return num
}
return num * factorial(num-1)
}

func main() {
fmt.Println(factorial(3))
fmt.Println(factorial(4))
fmt.Println(factorial(5))
}

Output:
>go run fact.go

24
120

7. Recursive function to find factorial of a number 1


8. Write a function that accepts
2 numbers and performs
addition, subtraction and
return both values
package main

import "fmt"

var x,y int


func calc(int,int) (int,int) {
return x + y, x - y
}

func main() {
fmt.Println("Enter 2 Numbers: ")
fmt.Scanln(&x,&y)
fmt.Println(calc(x,y))
}

Output:
go run func.go

Enter 2 Numbers:

25 20
45 5

8. Write a function that accepts 2 numbers and performs addition, subtraction and return both values 1
9. Write a function with one
variadic parameter that finds
the greatest number in a list of
n numbers
package main

import "fmt"

func greatestNumber(args ... int) int {


max := int(0)
for _, arg := range args {
if arg > max {
max = arg
}
}
return max
}

func main() {
fmt.Println(greatestNumber(12,3,84,32,52,97,6))
}

Output:
>go run variadicfunc.go
97

9. Write a function with one variadic parameter that finds the greatest number in a list of n numbers 1
10. Write a program to swap
two integers
package main

import "fmt"

func main() {
fmt.Println(myfunction())
}

func myfunction() []int {


a, b := 10, 5
b, a = a, b
return []int{a, b}
}

Output:
>go run swap.go
[5 10]

10. Write a program to swap two integers 1


11. Illustrate creation and
accessing a structure
package main

import "fmt"

type Address struct {


Name string
city string
Pincode int
}

func main() {
var a Address
fmt.Println(a)

a1 := Address{"Akshay", "Dehradun", 3623572}


fmt.Println("Address1: ", a1)

a2 := Address{Name: "Anikaa", city: "Ballia", Pincode: 277001}


fmt.Println("Address2: ", a2)

a3 := Address{Name: "Delhi"}
fmt.Println("Address3: ", a3)
}

Output:
>go run structures.go

{ 0}

Address1: {Akshay Dehradun 3623572}

Address2: {Anikaa Ballia 277001}


Address3: {Delhi 0}

11. Illustrate creation and accessing a structure 1


12. Program to demonstrate the
concept of Interfaces
package main

import "fmt"

type tank interface {


Tarea() float64
Volume() float64
}

type myvalue struct {


radius float64
height float64
}

func (m myvalue) Tarea() float64 {


return 2*m.radius*m.height +
2*3.14*m.radius*m.radius
}

func (m myvalue) Volume() float64 {


return 3.14 * m.radius * m.radius * m.height
}

func main() {
var t tank
t = myvalue{10, 14}
fmt.Println("Area of tank:", t.Tarea())
fmt.Println("Volume of tank:", t.Volume())
}

Output:
go run interfaces.go

Area of tank: 908


Volume of tank: 4396

12. Program to demonstrate the concept of Interfaces 1


13. Input the string ‘Hello
World’ and slice it into two
package main

import (
"fmt"
"strings"
)

func main() {
str1 := "Hello World"
fmt.Println("String 1: ", str1)

res1 := strings.SplitAfter(str1, " ")


fmt.Println("\nSliced String: ", res1)
}

Output:
>go run HW_slice.go
String 1:  Hello World

Sliced String:  [Hello  World]

13. Input the string ‘Hello World’ and slice it into two 1
14. Program to write a list of
cities to a new file
// Golang program to read and write the files
package main

// importing the packages


import (
"fmt"
"io/ioutil"
"log"
"os"
)

func CreateFile() {
fmt.Printf("Writing to a file in Go lang\n")
file, err := os.Create("test.txt")

if err != nil {
log.Fatalf("failed creating file: %s", err)
}

defer file.Close()

len, err := file.WriteString("Chennai\n Mumbai\n Delhi\n Trivandrum")

if err != nil {
log.Fatalf("failed writing to file: %s", err)
}

fmt.Printf("\nFile Name: %s", file.Name())


fmt.Printf("\nLength: %d bytes", len)
}

func ReadFile() {
fmt.Printf("\n\nReading a file in Go lang\n")
fileName := "test.txt"
data, err := ioutil.ReadFile("test.txt")
if err != nil {
log.Panicf("failed reading data from file: %s", err)
}
fmt.Printf("\nFile Name: %s", fileName)
fmt.Printf("\nSize: %d bytes", len(data))
fmt.Printf("\nData: %s", data)

// main function
func main() {
CreateFile()

14. Program to write a list of cities to a new file 1


ReadFile()
}

Output:
>go run CityFile.go
Writing to a file in Go lang

File Name: test.txt


Length: 34 bytes

Reading a file in Go lang

File Name: test.txt

Size: 34 bytes

Data: Chennai

Mumbai

Delhi
Trivandrum

14. Program to write a list of cities to a new file 2


15. Develop concurrent clock
server
Server Program

// Clock1 is a TCP server that periodically writes the time.


package main

import (
"io"
"log"
"net"
"time"
)

func main() {
listener, err := net.Listen("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err) // e.g., connection aborted
continue
}
go handleConn(conn) // handle one connection at a time
}
}

func handleConn(c net.Conn) {


defer c.Close()
for {
_, err := io.WriteString(c, time.Now().Format("15:04:05\n"))
if err != nil {
return // e.g., client disconnected
}
time.Sleep(1 * time.Second)
}
}

Client Program

package main

import (
"io"
"log"

15. Develop concurrent clock server 1


"net"
"os"
)

func main() {
conn, err := net.Dial("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
mustCopy(os.Stdout, conn)
}

func mustCopy(dst io.Writer, src io.Reader) {


if _, err := io.Copy(dst, src); err != nil {
log.Fatal(err)
}
}

Output:
13:58:54                        $ ./netcat1

13:58:55

13:58:56

^C

13:58:57

13:58:58

13:58:59

^C

15. Develop concurrent clock server 2


16. Send and receive data from
Channel
package main

import "fmt"

func sum(s []int, c chan int) {


sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}

func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}

Output:
-5 17 12

16. Send and receive data from Channel 1

You might also like