Trending February 2024 # Golang Program To Create Directories # Suggested March 2024 # Top 7 Popular

You are reading the article Golang Program To Create Directories updated in February 2024 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Golang Program To Create Directories

Golang has internal packages like os and io packages for creating a new directory. Here, we will create a directory using two examples. In the first example we will use os.Mkdir function and in the second example we will use ioutil.WriteFile function to execute the program.

Method 1: Using os.Mkdir Function

In this method, a directory named dirName variable is created using the os.Mkdir function. The permission bits for the new directory are the second input to os.Mkdir, which we set to 0755. (read, write, and execute permissions for the owner and read and execute permissions for others). The program will print “Directory created successfully!” if the directory creation is successful otherwise it will produce an error message.

Syntax os.Mkdir()

The os.Mkdir function in Go helps in creating a new directory with the specified name and permission bits (mode).

Algorithm

Step 1 − Create a package main and declare fmt(format package),and os package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a directoryname variable and assign it to the newdir one wants to create.

Step 3 − Use os.Mkdir function to create a new directory.

Step 4 − If an error persists while creating the directory, print the error on the console using fmt.Println() function where ln means new line and return.

Step 5 − If the directory is created successfully, Print the success message using the statement used in Step4.

Example

In this example we will use os.Mkdir function to create new directory.

package main import ( "fmt" "os" ) func main() { directoryname := "newdir" err := os.Mkdir(directoryname, 0755) if err != nil { fmt.Println(err) return } fmt.Println("Directory created successfully!") } Output Directory created successfully! Method 2: Using io/ioutil Package

In this method, an empty file with the name and permission bits is created using the ioutil.WriteFile function. If the function returns a nil error and the file is successfully created, we will print success. The WriteFile function will create the directory and if an error comes while creating a directory, we will print the error message.

Syntax Ioutil.WriteFile()

The ioutil.WriteFile function in Go is used to write a byte slice to a file.

Algorithm

Step 1 − Create a package main and declare fmt(format package), io/ioutil package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create the function main and in that function create a variable directoryname and assign it to newdir.

Step 3 − Use ioutil package function iouti.WriteFile function to create a directory.

Step 4 − If an error comes while creating the directory, print the error on the console and return.

Step 5 − If the directory is created successfully, print the success statement on the console.

Step 6 − The print statement is executed fmt.Println() function where ln means new line.

Example

In this example, we will use io/ioutil package function to create new directory.

package main import ( "fmt" "io/ioutil" ) func main() { directoryname := "newdir" err := ioutil.WriteFile(directoryname, []byte(""), 0755) if err != nil { fmt.Println(err) return } fmt.Println("Directory created successfully!") } Output Directory created successfully! Conclusion

We executed the program of creating a directory using two methods. In the first method we used os.Mkdir function and in the second method we used io/ioutil package to execute the program.

You're reading Golang Program To Create Directories

Golang Program To Create Multiple Begin And End Blocks

In this article, we will learn to write Go language programs that will create multiple BEGIN and END blocks using curly braces, “conditional statements”, as well as “external functions”.

A block is created using curly braces, the scope of a variable remains inside the block and not outside it.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

Step 2 − Create a main function

Step 3 − In the main, create a first block by initializing a variable

Step 4 − Print the a variable on the console for the first block

Step 5 − Create a second block by initializing a variable

Step 6 − Print the value of a variable on the console for the second block

Step 7 − Then, create a third block and initialize a variable in the block

Step 8 − Print the value of the a inside the third block

Step 9 − The print statement is executed the Println function from the fmt package where ln means new line

Example 1

In this Example, we will create a main function and, in that function, we will create multiple blocks using curly braces. In each block print the desired output on the console.

package main import "fmt" func main() { { a := 1 fmt.Println("Value of a inside first block is:", a) } { a := 2 fmt.Println("Value of a inside second block is:", a) } { a := 3 fmt.Println("Value of a inside third block is:", a) } } Output Value of a inside first block is: 1 Value of a inside second block is: 2 Value of a inside third block is: 3 Example 2

In this Example, a main function will be created and, in that function, create three blocks with if conditional statement in each block without any condition by setting the value true.

package main import "fmt" func main() { if true { a := 1 fmt.Println("Value of a inside first block is:", a) } if true { a := 2 fmt.Println("Value of a inside second block is:", a) } if true { a := 3 fmt.Println("Value of a inside third block is:", a) } } Output Value of a inside first block is: 1 Value of a inside second block is: 2 Value of a inside third block is: 3 Example 3

In this Example, we will write a Go language program to create multiple BEGIN and END blocks using three external functions.

package main import "fmt" func main() { firstBlock() secondBlock() thirdBlock() } func firstBlock() { a := 1 fmt.Println("Value of a inside first block is:", a) } func secondBlock() { a := 2 fmt.Println("Value of a inside second block:", a) } func thirdBlock() { a := 3 fmt.Println("Value of a inside third block:", a) } Output Value of a inside first block is: 1 Value of a inside second block: 2 Value of a inside third block: 3 Conclusion

We executed the program of creating multiple BEGIN and END blocks. In the first Example, we used multiple curly braces to create multiple blocks whereas in the second Example we used if conditional statement with no condition and in the third Example we used external functions to execute the program.

Golang Program To Compare Elements In Two Slices

In this tutorial, we will learn how to compare elements in two slices. In slices a simple equality comparison is not possible so the slices are compared with their lengths and the elements present in the loop. The output will be printed in the form of Boolean value on the console with the help of fmt.Println() function. Let’s see how to execute this with the help of an example.

Method 1: Using a user-defined function

In this method, we will compare elements in two slices using an external function and, in that function, we will set some conditions, if the slices satisfy those conditions, they will be considered equal else they won’t be considered equal. Let’s have a look to get a better understanding.

Syntax func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt package in the program.

Step 2 − Create a main function, in it create two slices of type string and call a function named slice_equality with two slices as arguments.

Step 3 − Create a function slice_equality and in that function check if the length of the first slice is not equal to the second slice return false.

Step 4 − In the next case run a for loop till the range of str1 and check if the elements of str2 are equal to str1, if they are not equal return false.

Step 5 − After checking all the conditions set in the algorithm, if not even once false is returned, return true to the function.

Step 6 − Print the Boolean value using fmt.Println() function where ln refers to the next line here.

Example

Golang program to compare elements in two slices using custom function

package main import "fmt" func slice_equality(str1, str2 []string) bool { if len(str1) != len(str2) { return false } for i, str := range str1 { if str != str2[i] { return false } } return true } func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The slices are equal or not before adding any element:") fmt.Println(slice_equality(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The slices are equal or not after adding another element:") fmt.Println(slice_equality(str1, str2)) } Output The slices are equal or not before adding any element: true The slices are equal or not after adding another element: false Method 2: Using built-in function

In this method, we will use reflect.DeepEqual() function to compare two slices recursively. Built-in functions ease our work and shorten the code. The output here will be printed using fmt.Println() function. Let’s have a look and inculcate how to solve this problem.

Syntax reflect.DeepEqual()

This function compares two values recursively. It traverses and check the equality of the corresponding data values at each level. However, the solution is less safe as compared to comparison in loops. Reflect should be used with care and should be used in those cases where it’s of utmost importance.

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

Step 1 − Create a package main and import fmt and reflect package in the program.

Step 2 − Create a function main and in that function create two slices of type string which are to be compared with each other.

Step 3 − In the first case before adding any new element in the slice, compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 4 − In the second case add new string in the slice and compare the slices using reflect.DeepEqual() function with the slices as parameters.

Step 5 − The output will be printed using fmt.Prinln() function on the console as a Boolean value.

Example

Golang program to compare elements in two slices using built-in function

package main import ( "fmt" "reflect" ) func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The strings are equal or not before adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The strings are equal or not after adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) } Output The strings are equal or not before adding any element: true The strings are equal or not after adding any element: false Conclusion

In this tutorial, of comparing slices, we used two methods to execute the program. In the first method we used custom function with some conditions and in the second method we used a built-in function named reflect.DeepEqual() function.

Golang Program To Convert Int Type Variables To String

In this tutorial we will learn how to convert int type variables to string variables using Golang programming language.

A string is defined as the sequence of one or more characters (letters, numbers, or symbols). Computer applications frequently use strings as a data type thus, there is a need to convert strings to numbers or numbers to strings at manny places specially when we are using data entered by the user.

Syntax func Itoa(x int) string

Itoa() function in go programming language is used to get the string representation of any integer value here it is depicted by x. This function takes an integer value as an argument and returns the corresponding string representation of that number.

INPUT − int type

OUTPUT − string

Example: Golang program to convert int type variables to strings using iota() function

Using the strconv.Itoa() method from the strconv package in the Go standard library, we can convert numbers to strings. A numeric value will be changed into a string value if it is passed into the method’s parentheses as a number or variable.

Algorithm

STEP 1 − Import the package fmt and strconv.

STEP 2 − Start the function main()

STEP 3 − Initialize the integer variables and assign appropriate values to them.

STEP 4 − Print the data type of variable

STEP 5 − Use the strconv.Itoa() function to convert the integer type value to string.

STEP 6 − Store the result in a separate variable

STEP 7 − Print the result on the screen using fmt.Println() function

Example

package

main

import

(

“fmt”

“strconv”

)

func

main

(

)

{

number

:

=

20

fmt

.

Printf

(

“Type of variable before conversion: %T nValue : %vn”

,

number

,

number

)

result

:

=

strconv

.

Itoa

(

number

)

fmt

.

Printf

(

“Type of variable after conversion : %T nValue : %vn”

,

result

,

result

)

}

Output Type of variable before conversion: int Value : 20 Type of variable after conversion : string Value : 20

The quotation marks around the number 12 indicate that it is now a string value rather than an integer.

Description of the Code

In the above program, we first declare the package main.

We imported the fmt package that includes the files of package fmt. We also imported Package strconv implements conversions to and from string representations of basic data types.

Now we initialize a int type variable and store a value.

Next we call the function Itoa() and pass the respective integer value as an argument to it. It converts the int type variable to a string type variable.

Store the result in a separate variable and print the result on the screen using fmt.Println() function.

To print the result we can contrast the data types of the variable before and after the conversion process.

Example: Golang program to convert int type variables to strings using Sprintf() function: Syntax func Sprintf(format string, a ...interface{}) string

This function returns a formatted string. The first argument should be a string format followed by a variable number of arguments. This function then returns the result as a formatted string format.

Algorithm

STEP 1 − Import the package fmt and strconv package.

STEP 2 − Start the function main()

STEP 3 − Initialize the integer variable and assign value to it.

STEP 4 − Print the type of variable.

STEP 5 − Use the Sprintf() function to convert integer type value to string.

STEP 6 − Print the type of variable again after the conversion process.

Example

package

main

import

(

“fmt”

“reflect”

)

func

main

(

)

{

number

:

=

200

fmt

.

Println

(

“Number =”

,

number

)

var

num

=

reflect

.

TypeOf

(

number

)

fmt

.

Println

(

“Type of variable before conversion =”

,

num

)

result

:

=

fmt

.

Sprintf

(

“%s”

,

number

)

var

res

=

reflect

.

TypeOf

(

result

)

fmt

.

Println

(

“Type of Variable = “

,

res

)

fmt

.

Println

(

“Value =”

,

result

)

}

Output Number = 200 Type of variable before conversion = int Type of Variable = string Value = %!s(int=200) Description of the Code

First declare the package main.

Import the fmt package that allows us to print anything on the screen.

Now initialize a variable called number of type integer and assign appropriate value to it.

Now use Sprintf() function to convert the integer type value to string and pass the integer number as an argument to it.

Store the output in a separate variable here we have named it as result.

Print the data type of the result variable along with the value it possesses on the screen using fmt.Ptintln() function.

Conclusion

We have successfully compiled and executed the Golang program code to convert int type variables to string type variables along with the examples.

Golang Program To Show Overriding Of Methods In Classes

When a method is overridden in Go, a new method with the same name and receiver type as an existing method is created and used in place of the existing one. As a result, Golang may provide polymorphism, allowing different implementations of a same method to be used depending on the type of receiver. Let’ see the execution in examples.

Method 1: Using shape struct

Here, this shape struct will contain an area field and an area method which will return the value of area field. Rectangle and square both inherit the area () method. The output will be their area printed on the console.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program

Step 2 − First, we create a struct Shape with a field called area of type float64 and a method called Area() that returns the field’s value.

Step 3 − The Shape struct is then embedded in a new structure called Rectangle, which also has two float64-type properties called width and height.

Step 4 − Then, we create a function for the Rectangle struct called CalculateArea() that computes the area using the width and height variables and assigns the result to the area field that was inherited from the Shape struct.

Step 5 − The Shape struct is also embedded in the Square struct, which similarly has a field side of type float64.

Step 6 − Then, using the side field to compute the area and assigning the result to the area field inherited from the Shape struct, we define the method CalculateArea() for the Square struct.

Step 7 − To compute the areas of the forms, we construct pointers to instances of the Rectangle and Square structs in the main function and call their respective CalculateArea() functions.

Step 8 − We invoke the Area() function on the Rectangle and Square pointers to obtain the areas of the forms after computing their areas.

Step 9 − The area of rectangle and the area of square is printed on the console using fmt.Println() function where ln means new line.

Example

In this example we will learn how to override methods in class using shape struct.

package main import ( "fmt" ) type Shape struct { area float64 } func (sq *Shape) Area() float64 { return chúng tôi } type Rectangle struct { Shape width float64 height float64 } func (rect *Rectangle) CalculateArea() { rect.area = rect.width * rect.height } type Square struct { Shape side float64 } func (sq *Square) CalculateArea() { sq.area = chúng tôi * chúng tôi } func main() { rect := &Rectangle{width: 16, height: 6} rect.CalculateArea() fmt.Println("Area of rectangle: ", rect.Area()) sq := &Square{side: 8} sq.CalculateArea() fmt.Println("Area of square: ", sq.Area()) } Output Area of rectangle: 96 Area of square: 64 Method 2: Using shape interface

Here, the shapes rectangle and square implement the shape interface by implementing the area method. In the end, the output will be the area of square and rectangle.

Algorithm

Step 1 − Create a package main and declare fmt(format package) package in the program

Step 2 − In the beginning, we create an interface called Shape with a function called Area() that returns a float64 value.

Step 3 − We then define a structure called Rectangle, which has two float64-type attributes called width and height.

Step 4 − The Area() method for the Rectangle struct is then implemented by creating a function with the same signature as the Shape interface and computing the area using the width and height parameters.

Step 5 − In a similar manner, we create a structure called Square with a field of type float64.

Step 6 − Then, using the side field to determine the area this time, we implement the Area() method for the Square struct.

Step 7 − The Rectangle struct’s Area() method is called in the main function, and it returns the area of the rectangle.

Step 8 − Additionally, we construct an instance of the Square struct and use its Area() method to obtain the square’s area.

Step 9 − The area of both the shapes is printed on the console using fmt.Println() function where ln means new line.

Example

In this example we will learn how to override methods in class using shape interface.

package main import ( "fmt" ) type Shape interface { Area() float64 } type Rectangle struct { width float64 height float64 } func (rect Rectangle) Area() float64 { return rect.width * rect.height } type Square struct { side float64 } func (sq Square) Area() float64 { return chúng tôi * chúng tôi } func main() { rect := Rectangle{width: 16, height: 6} fmt.Println("Area of rectangle: ", rect.Area()) sq := Square{side: 8} fmt.Println("Area of square: ", sq.Area()) } Output Area of rectangle: 96 Area of square: 64 Conclusion

We executed the program of showing how to override methods in class using two examples. In the first example we used shape struct and in the second example we used shape interface.

Golang Program To Remove Repeated Elements From An Array

In this tutorial, we will write a go language program to remove duplicate elements from an array. By removing the duplicate entries, we mean that we wish to remove a value repeating multiple times. In this tutorial, we are using examples of an array of integers as well as an array of strings.

Method 1: Remove Duplicate Values from an Array using an External Function

The following code illustrates how we can remove duplicate values from an array of integers using a user-defined function.

Algorithm

Step 1 − First, we need to import the fmt package.

Step 2 − Now, make a function named removeDuplicate() that accepts an array as an argument and returns an array after removing all the duplicate entries.

Step 3 − This function uses a for loop to iterate over the array.

Step 4 − Here we have created a map that has keys as integers and values as Boolean by default the values stored by the map_var are false.

Step 5 − During each iteration from the array, we are checking the value of map_var if it is false then we have to take that value and append it into the new array created above.

Step 6 − Repeat this process until all the array values are checked and then return the new array just formed.

Step 7 − Now, we need to start the main function.

Step 8 − Initialize an array arr of integers, store values to it, and print the array on the screen.

Step 9 − Now call the removeDuplicate function by passing the array created above as an argument to it.

Step 10 − Store the result obtained in an array called result and print the array on the screen.

Example

Golang program to remove duplicate values from an array using an external function.

package main import "fmt" func removeDuplicate(arr [8]int) []int { map_var := map[int]bool{} result := []int{} for e := range arr { if map_var[arr[e]] != true { map_var[arr[e]] = true result = append(result, arr[e]) } } return result } func main() { arr := [8]int{1, 2, 2, 4, 4, 5, 7, 5} fmt.Println("The unsorted array entered is:", arr) result := removeDuplicate(arr) fmt.Println("The array obtained after removing the duplicate values is:", result) } Output The unsorted array entered is: [1 2 2 4 4 5 7 5] The array obtained after removing the duplicate values is: [1 2 4 5 7] Method 2: Remove Duplicate Elements from an Array without using the Maps

Let us now look at another example of how we can remove duplicate entries from an array without using the maps.

Algorithm

Step 1 − Import the fmt package that allows us to print anything on the screen.

Step 2 − Call the main() function.

Step 3 − Initialize and store the elements in an array of integers and print it on the screen.

Step 4 − Iterate over the array using for loops to check if the current element is equal to the next element or not.

Step 5 − If both the elements are equal then remove the duplicate element using the for loop and decrement the size of the array by 1 by doing size–

Step 6 − Once iterated over the whole array print the elements of the new array obtained on the screen using fmt.Println() function.

Example

GoLang Program to Remove Duplicate Elements from an Array.

package main import "fmt" func main() { arr := []int{1, 2, 2, 4, 4, 5, 7, 5} fmt.Println("The unsorted array entered is:", arr) size := len(arr) for i := 0; i < size; i++ { for j := i + 1; j < size; j++ { if arr[i] == arr[j] { for k := j; k < size-1; k++ { arr[k] = arr[k+1] } size-- j-- } } } fmt.Println("The elements of array obtained after removing the duplicate values is:") for i := 0; i < size; i++ { fmt.Println(arr[i]) } } Output The unsorted array entered is: [1 2 2 4 4 5 7 5] The elements of array obtained after removing the duplicate values is: 1 2 4 5 7 Conclusion

We have successfully compiled and executed a golang program to remove duplicate elements from an array along with examples.

Update the detailed information about Golang Program To Create Directories on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!