Dr. D. Y.
Patil Unitech society’s
Dr. D. Y. Patil Arts, Commerce and Science College, Pimpri, Pune-18
Computer Science Department
Academic Year: 2023-24
T.Y.B.C.A.(Science) Sem-VI
Subject: Programming in GO
Practical Assignment – 07
Date: 16th March 2024
1. Write a program in GO language to create a user defined package to
find out the area of a rectangle.
Solution:-
// rectangle.go
package geometry
// Area returns the area of a rectangle given its length and width
func Area(length, width float64) float64 {
return length * width
}
// main.go
package main
import (
"fmt"
"geometry" // Import the user-defined package
)
func main() {
length := 5.0
width := 3.0
// Calculate the area of the rectangle using the user-defined
package
area := geometry.Area(length, width)
fmt.Printf("Area of the rectangle with length %.2f and width
%.2f: %.2f\n", length, width, area)
}
2. Write a program in GO language using a user defined package
calculator that performs one calculator operation as per the user's
choice.
Solution:-
// calculator.go
package calculator
import "errors"
// Operation represents a calculator operation
type Operation int
const (
Addition Operation = iota
Subtraction
Multiplication
Division
)
// Calculate performs the specified operation on two numbers
func Calculate(operation Operation, num1, num2 float64) (float64, error) {
switch operation {
case Addition:
return num1 + num2, nil
case Subtraction:
return num1 - num2, nil
case Multiplication:
return num1 * num2, nil
case Division:
if num2 == 0 {
return 0, errors.New("division by zero")
}
return num1 / num2, nil
default:
return 0, errors.New("unsupported operation")
}
}
// main.go
package main
import (
"fmt"
"calculator" // Import the user-defined package
)
func main() {
num1 := 10.0
num2 := 5.0
operation := calculator.Addition // Change this to the desired operation
result, err := calculator.Calculate(operation, num1, num2)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Result of %.2f %s %.2f: %.2f\n", num1,
getOperationSymbol(operation), num2, result)
}
func getOperationSymbol(operation calculator.Operation) string {
switch operation {
case calculator.Addition:
return "+"
case calculator.Subtraction:
return "-"
case calculator.Multiplication:
return "*"
case calculator.Division:
return "/"
default:
return "?"
}
}
3. Write a function in GO language to find the square of a number and
write a benchmark for it.
Solution:-
package main
import (
"fmt"
"testing"
)
// Square returns the square of a given number
func Square(x int) int {
return x * x
}
func TestSquare(t *testing.T) {
tests := []struct {
input int
expected int
}{
{0, 0},
{1, 1},
{-2, 4},
{5, 25},
}
for _, test := range tests {
result := Square(test.input)
if result != test.expected {
t.Errorf("Square(%d) = %d; want %d", test.input,
result, test.expected)
}
}
}
func BenchmarkSquare(b *testing.B) {
for i := 0; i < b.N; i++ {
Square(10) // Square of number 10
}
}
func main() {
fmt.Println(Square(5)) // Test the function with an example
}
To run the code use this command :-
go test -bench=.
4. Write a program in GO language to print file information.
Solution:-
package main
import (
"fmt"
"os"
)
func main() {
// Specify the file path
filePath := "example.txt"
// Get file information
fileInfo, err := os.Stat(filePath)
if err != nil {
fmt.Println("Error:", err)
return
}
// Print file information
fmt.Println("File Name:", fileInfo.Name())
fmt.Println("Size (bytes):", fileInfo.Size())
fmt.Println("Mode:", fileInfo.Mode())
fmt.Println("Last Modified:", fileInfo.ModTime())
fmt.Println("Is Directory:", fileInfo.IsDir())
}
5. Write a program in GO language program to create Text file.
Solution:-
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Specify the file name
fileName := "output.txt"
// Create the file
file, err := os.Create(fileName)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
// Write content to the file
content := "Hello, this is a text file created using Go programming
language."
writer := bufio.NewWriter(file)
_, err = writer.WriteString(content)
if err != nil {
fmt.Println("Error:", err)
return
}
writer.Flush()
fmt.Println("Text file", fileName, "has been created successfully.")
}
6. Write a program in GO language to read XML file into structure and
display structure.
Solution:-
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
// Define a struct that matches the structure of the XML file
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age"`
City string `xml:"city"`
}
func main() {
// Open the XML file
xmlFile, err := os.Open("example.xml")
if err != nil {
fmt.Println("Error opening XML file:", err)
return
}
defer xmlFile.Close()
// Read the XML file content
byteValue, err := ioutil.ReadAll(xmlFile)
if err != nil {
fmt.Println("Error reading XML file:", err)
return
}
// Define a variable to store the decoded XML data
var person Person
// Unmarshal the XML data into the structure
err = xml.Unmarshal(byteValue, &person)
if err != nil {
fmt.Println("Error unmarshalling XML:", err)
return
}
// Print the structure
fmt.Println("Name:", person.Name)
fmt.Println("Age:", person.Age)
fmt.Println("City:", person.City)
}
7. Write a program in GO language to add or append content at the end of
a text file.
Solution:-
package main
import (
"fmt"
"os"
)
func appendToFile(fileName string, content string) error {
// Open the file in append mode with write-only permission and
create it if it doesn't exist
file, err := os.OpenFile(fileName,
os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
// Write the content to the end of the file
if _, err := file.WriteString(content); err != nil {
return err
}
return nil
}
func main() {
fileName := "example.txt"
content := "This content will be appended to the end of the file.\n"
err := appendToFile(fileName, content)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Content has been successfully appended to the file:",
fileName)
}
8. Write a program in the GO language program to open a file in READ
only mode.
Solution:-
package main
import (
"fmt"
"os"
)
func main() {
// Specify the file path
filePath := "example.txt"
// Open the file in read-only mode
file, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
fmt.Println("File", filePath, "opened successfully in read-only
mode.")
}
9. Write a program in Go language to add or append content at the end of
a text file.
Solution:-
package main
import (
"fmt"
"os"
)
func appendToFile(fileName, content string) error {
// Open the file in append mode with write-only permission
file, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY,
0644)
if err != nil {
return err
}
defer file.Close()
// Write the content at the end of the file
if _, err := file.WriteString(content); err != nil {
return err
}
return nil
}
func main() {
fileName := "example.txt"
content := "\nThis is the content to be appended."
err := appendToFile(fileName, content)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Content has been successfully appended to the file:",
fileName)
}